core.c 80 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Data Access Monitor
  4. *
  5. * Author: SeongJae Park <sj@kernel.org>
  6. */
  7. #define pr_fmt(fmt) "damon: " fmt
  8. #include <linux/damon.h>
  9. #include <linux/delay.h>
  10. #include <linux/kthread.h>
  11. #include <linux/memcontrol.h>
  12. #include <linux/mm.h>
  13. #include <linux/psi.h>
  14. #include <linux/slab.h>
  15. #include <linux/string.h>
  16. #include <linux/string_choices.h>
  17. #define CREATE_TRACE_POINTS
  18. #include <trace/events/damon.h>
  19. static DEFINE_MUTEX(damon_lock);
  20. static int nr_running_ctxs;
  21. static bool running_exclusive_ctxs;
  22. static DEFINE_MUTEX(damon_ops_lock);
  23. static struct damon_operations damon_registered_ops[NR_DAMON_OPS];
  24. static struct kmem_cache *damon_region_cache __ro_after_init;
  25. /* Should be called under damon_ops_lock with id smaller than NR_DAMON_OPS */
  26. static bool __damon_is_registered_ops(enum damon_ops_id id)
  27. {
  28. struct damon_operations empty_ops = {};
  29. if (!memcmp(&empty_ops, &damon_registered_ops[id], sizeof(empty_ops)))
  30. return false;
  31. return true;
  32. }
  33. /**
  34. * damon_is_registered_ops() - Check if a given damon_operations is registered.
  35. * @id: Id of the damon_operations to check if registered.
  36. *
  37. * Return: true if the ops is set, false otherwise.
  38. */
  39. bool damon_is_registered_ops(enum damon_ops_id id)
  40. {
  41. bool registered;
  42. if (id >= NR_DAMON_OPS)
  43. return false;
  44. mutex_lock(&damon_ops_lock);
  45. registered = __damon_is_registered_ops(id);
  46. mutex_unlock(&damon_ops_lock);
  47. return registered;
  48. }
  49. /**
  50. * damon_register_ops() - Register a monitoring operations set to DAMON.
  51. * @ops: monitoring operations set to register.
  52. *
  53. * This function registers a monitoring operations set of valid &struct
  54. * damon_operations->id so that others can find and use them later.
  55. *
  56. * Return: 0 on success, negative error code otherwise.
  57. */
  58. int damon_register_ops(struct damon_operations *ops)
  59. {
  60. int err = 0;
  61. if (ops->id >= NR_DAMON_OPS)
  62. return -EINVAL;
  63. mutex_lock(&damon_ops_lock);
  64. /* Fail for already registered ops */
  65. if (__damon_is_registered_ops(ops->id))
  66. err = -EINVAL;
  67. else
  68. damon_registered_ops[ops->id] = *ops;
  69. mutex_unlock(&damon_ops_lock);
  70. return err;
  71. }
  72. /**
  73. * damon_select_ops() - Select a monitoring operations to use with the context.
  74. * @ctx: monitoring context to use the operations.
  75. * @id: id of the registered monitoring operations to select.
  76. *
  77. * This function finds registered monitoring operations set of @id and make
  78. * @ctx to use it.
  79. *
  80. * Return: 0 on success, negative error code otherwise.
  81. */
  82. int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id)
  83. {
  84. int err = 0;
  85. if (id >= NR_DAMON_OPS)
  86. return -EINVAL;
  87. mutex_lock(&damon_ops_lock);
  88. if (!__damon_is_registered_ops(id))
  89. err = -EINVAL;
  90. else
  91. ctx->ops = damon_registered_ops[id];
  92. mutex_unlock(&damon_ops_lock);
  93. return err;
  94. }
  95. /*
  96. * Construct a damon_region struct
  97. *
  98. * Returns the pointer to the new struct if success, or NULL otherwise
  99. */
  100. struct damon_region *damon_new_region(unsigned long start, unsigned long end)
  101. {
  102. struct damon_region *region;
  103. region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL);
  104. if (!region)
  105. return NULL;
  106. region->ar.start = start;
  107. region->ar.end = end;
  108. region->nr_accesses = 0;
  109. region->nr_accesses_bp = 0;
  110. INIT_LIST_HEAD(&region->list);
  111. region->age = 0;
  112. region->last_nr_accesses = 0;
  113. return region;
  114. }
  115. void damon_add_region(struct damon_region *r, struct damon_target *t)
  116. {
  117. list_add_tail(&r->list, &t->regions_list);
  118. t->nr_regions++;
  119. }
  120. static void damon_del_region(struct damon_region *r, struct damon_target *t)
  121. {
  122. list_del(&r->list);
  123. t->nr_regions--;
  124. }
  125. static void damon_free_region(struct damon_region *r)
  126. {
  127. kmem_cache_free(damon_region_cache, r);
  128. }
  129. void damon_destroy_region(struct damon_region *r, struct damon_target *t)
  130. {
  131. damon_del_region(r, t);
  132. damon_free_region(r);
  133. }
  134. static bool damon_is_last_region(struct damon_region *r,
  135. struct damon_target *t)
  136. {
  137. return list_is_last(&r->list, &t->regions_list);
  138. }
  139. /*
  140. * Check whether a region is intersecting an address range
  141. *
  142. * Returns true if it is.
  143. */
  144. static bool damon_intersect(struct damon_region *r,
  145. struct damon_addr_range *re)
  146. {
  147. return !(r->ar.end <= re->start || re->end <= r->ar.start);
  148. }
  149. /*
  150. * Fill holes in regions with new regions.
  151. */
  152. static int damon_fill_regions_holes(struct damon_region *first,
  153. struct damon_region *last, struct damon_target *t)
  154. {
  155. struct damon_region *r = first;
  156. damon_for_each_region_from(r, t) {
  157. struct damon_region *next, *newr;
  158. if (r == last)
  159. break;
  160. next = damon_next_region(r);
  161. if (r->ar.end != next->ar.start) {
  162. newr = damon_new_region(r->ar.end, next->ar.start);
  163. if (!newr)
  164. return -ENOMEM;
  165. damon_insert_region(newr, r, next, t);
  166. }
  167. }
  168. return 0;
  169. }
  170. /*
  171. * damon_set_regions() - Set regions of a target for given address ranges.
  172. * @t: the given target.
  173. * @ranges: array of new monitoring target ranges.
  174. * @nr_ranges: length of @ranges.
  175. * @min_region_sz: minimum region size.
  176. *
  177. * This function adds new regions to, or modify existing regions of a
  178. * monitoring target to fit in specific ranges.
  179. *
  180. * Return: 0 if success, or negative error code otherwise.
  181. */
  182. int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
  183. unsigned int nr_ranges, unsigned long min_region_sz)
  184. {
  185. struct damon_region *r, *next;
  186. unsigned int i;
  187. int err;
  188. /* Remove regions which are not in the new ranges */
  189. damon_for_each_region_safe(r, next, t) {
  190. for (i = 0; i < nr_ranges; i++) {
  191. if (damon_intersect(r, &ranges[i]))
  192. break;
  193. }
  194. if (i == nr_ranges)
  195. damon_destroy_region(r, t);
  196. }
  197. r = damon_first_region(t);
  198. /* Add new regions or resize existing regions to fit in the ranges */
  199. for (i = 0; i < nr_ranges; i++) {
  200. struct damon_region *first = NULL, *last, *newr;
  201. struct damon_addr_range *range;
  202. range = &ranges[i];
  203. /* Get the first/last regions intersecting with the range */
  204. damon_for_each_region_from(r, t) {
  205. if (damon_intersect(r, range)) {
  206. if (!first)
  207. first = r;
  208. last = r;
  209. }
  210. if (r->ar.start >= range->end)
  211. break;
  212. }
  213. if (!first) {
  214. /* no region intersects with this range */
  215. newr = damon_new_region(
  216. ALIGN_DOWN(range->start,
  217. min_region_sz),
  218. ALIGN(range->end, min_region_sz));
  219. if (!newr)
  220. return -ENOMEM;
  221. damon_insert_region(newr, damon_prev_region(r), r, t);
  222. } else {
  223. /* resize intersecting regions to fit in this range */
  224. first->ar.start = ALIGN_DOWN(range->start,
  225. min_region_sz);
  226. last->ar.end = ALIGN(range->end, min_region_sz);
  227. /* fill possible holes in the range */
  228. err = damon_fill_regions_holes(first, last, t);
  229. if (err)
  230. return err;
  231. }
  232. }
  233. return 0;
  234. }
  235. struct damos_filter *damos_new_filter(enum damos_filter_type type,
  236. bool matching, bool allow)
  237. {
  238. struct damos_filter *filter;
  239. filter = kmalloc_obj(*filter);
  240. if (!filter)
  241. return NULL;
  242. filter->type = type;
  243. filter->matching = matching;
  244. filter->allow = allow;
  245. INIT_LIST_HEAD(&filter->list);
  246. return filter;
  247. }
  248. /**
  249. * damos_filter_for_ops() - Return if the filter is ops-handled one.
  250. * @type: type of the filter.
  251. *
  252. * Return: true if the filter of @type needs to be handled by ops layer, false
  253. * otherwise.
  254. */
  255. bool damos_filter_for_ops(enum damos_filter_type type)
  256. {
  257. switch (type) {
  258. case DAMOS_FILTER_TYPE_ADDR:
  259. case DAMOS_FILTER_TYPE_TARGET:
  260. return false;
  261. default:
  262. break;
  263. }
  264. return true;
  265. }
  266. void damos_add_filter(struct damos *s, struct damos_filter *f)
  267. {
  268. if (damos_filter_for_ops(f->type))
  269. list_add_tail(&f->list, &s->ops_filters);
  270. else
  271. list_add_tail(&f->list, &s->core_filters);
  272. }
  273. static void damos_del_filter(struct damos_filter *f)
  274. {
  275. list_del(&f->list);
  276. }
  277. static void damos_free_filter(struct damos_filter *f)
  278. {
  279. kfree(f);
  280. }
  281. void damos_destroy_filter(struct damos_filter *f)
  282. {
  283. damos_del_filter(f);
  284. damos_free_filter(f);
  285. }
  286. struct damos_quota_goal *damos_new_quota_goal(
  287. enum damos_quota_goal_metric metric,
  288. unsigned long target_value)
  289. {
  290. struct damos_quota_goal *goal;
  291. goal = kmalloc_obj(*goal);
  292. if (!goal)
  293. return NULL;
  294. goal->metric = metric;
  295. goal->target_value = target_value;
  296. INIT_LIST_HEAD(&goal->list);
  297. return goal;
  298. }
  299. void damos_add_quota_goal(struct damos_quota *q, struct damos_quota_goal *g)
  300. {
  301. list_add_tail(&g->list, &q->goals);
  302. }
  303. static void damos_del_quota_goal(struct damos_quota_goal *g)
  304. {
  305. list_del(&g->list);
  306. }
  307. static void damos_free_quota_goal(struct damos_quota_goal *g)
  308. {
  309. kfree(g);
  310. }
  311. void damos_destroy_quota_goal(struct damos_quota_goal *g)
  312. {
  313. damos_del_quota_goal(g);
  314. damos_free_quota_goal(g);
  315. }
  316. /* initialize fields of @quota that normally API users wouldn't set */
  317. static struct damos_quota *damos_quota_init(struct damos_quota *quota)
  318. {
  319. quota->esz = 0;
  320. quota->total_charged_sz = 0;
  321. quota->total_charged_ns = 0;
  322. quota->charged_sz = 0;
  323. quota->charged_from = 0;
  324. quota->charge_target_from = NULL;
  325. quota->charge_addr_from = 0;
  326. quota->esz_bp = 0;
  327. return quota;
  328. }
  329. struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
  330. enum damos_action action,
  331. unsigned long apply_interval_us,
  332. struct damos_quota *quota,
  333. struct damos_watermarks *wmarks,
  334. int target_nid)
  335. {
  336. struct damos *scheme;
  337. scheme = kmalloc_obj(*scheme);
  338. if (!scheme)
  339. return NULL;
  340. scheme->pattern = *pattern;
  341. scheme->action = action;
  342. scheme->apply_interval_us = apply_interval_us;
  343. /*
  344. * next_apply_sis will be set when kdamond starts. While kdamond is
  345. * running, it will also updated when it is added to the DAMON context,
  346. * or damon_attrs are updated.
  347. */
  348. scheme->next_apply_sis = 0;
  349. scheme->walk_completed = false;
  350. INIT_LIST_HEAD(&scheme->core_filters);
  351. INIT_LIST_HEAD(&scheme->ops_filters);
  352. scheme->stat = (struct damos_stat){};
  353. scheme->max_nr_snapshots = 0;
  354. INIT_LIST_HEAD(&scheme->list);
  355. scheme->quota = *(damos_quota_init(quota));
  356. /* quota.goals should be separately set by caller */
  357. INIT_LIST_HEAD(&scheme->quota.goals);
  358. scheme->wmarks = *wmarks;
  359. scheme->wmarks.activated = true;
  360. scheme->migrate_dests = (struct damos_migrate_dests){};
  361. scheme->target_nid = target_nid;
  362. return scheme;
  363. }
  364. static void damos_set_next_apply_sis(struct damos *s, struct damon_ctx *ctx)
  365. {
  366. unsigned long sample_interval = ctx->attrs.sample_interval ?
  367. ctx->attrs.sample_interval : 1;
  368. unsigned long apply_interval = s->apply_interval_us ?
  369. s->apply_interval_us : ctx->attrs.aggr_interval;
  370. s->next_apply_sis = ctx->passed_sample_intervals +
  371. apply_interval / sample_interval;
  372. }
  373. void damon_add_scheme(struct damon_ctx *ctx, struct damos *s)
  374. {
  375. list_add_tail(&s->list, &ctx->schemes);
  376. damos_set_next_apply_sis(s, ctx);
  377. }
  378. static void damon_del_scheme(struct damos *s)
  379. {
  380. list_del(&s->list);
  381. }
  382. static void damon_free_scheme(struct damos *s)
  383. {
  384. kfree(s);
  385. }
  386. void damon_destroy_scheme(struct damos *s)
  387. {
  388. struct damos_quota_goal *g, *g_next;
  389. struct damos_filter *f, *next;
  390. damos_for_each_quota_goal_safe(g, g_next, &s->quota)
  391. damos_destroy_quota_goal(g);
  392. damos_for_each_core_filter_safe(f, next, s)
  393. damos_destroy_filter(f);
  394. damos_for_each_ops_filter_safe(f, next, s)
  395. damos_destroy_filter(f);
  396. kfree(s->migrate_dests.node_id_arr);
  397. kfree(s->migrate_dests.weight_arr);
  398. damon_del_scheme(s);
  399. damon_free_scheme(s);
  400. }
  401. /*
  402. * Construct a damon_target struct
  403. *
  404. * Returns the pointer to the new struct if success, or NULL otherwise
  405. */
  406. struct damon_target *damon_new_target(void)
  407. {
  408. struct damon_target *t;
  409. t = kmalloc_obj(*t);
  410. if (!t)
  411. return NULL;
  412. t->pid = NULL;
  413. t->nr_regions = 0;
  414. INIT_LIST_HEAD(&t->regions_list);
  415. INIT_LIST_HEAD(&t->list);
  416. t->obsolete = false;
  417. return t;
  418. }
  419. void damon_add_target(struct damon_ctx *ctx, struct damon_target *t)
  420. {
  421. list_add_tail(&t->list, &ctx->adaptive_targets);
  422. }
  423. bool damon_targets_empty(struct damon_ctx *ctx)
  424. {
  425. return list_empty(&ctx->adaptive_targets);
  426. }
  427. static void damon_del_target(struct damon_target *t)
  428. {
  429. list_del(&t->list);
  430. }
  431. void damon_free_target(struct damon_target *t)
  432. {
  433. struct damon_region *r, *next;
  434. damon_for_each_region_safe(r, next, t)
  435. damon_free_region(r);
  436. kfree(t);
  437. }
  438. void damon_destroy_target(struct damon_target *t, struct damon_ctx *ctx)
  439. {
  440. if (ctx && ctx->ops.cleanup_target)
  441. ctx->ops.cleanup_target(t);
  442. damon_del_target(t);
  443. damon_free_target(t);
  444. }
  445. unsigned int damon_nr_regions(struct damon_target *t)
  446. {
  447. return t->nr_regions;
  448. }
  449. struct damon_ctx *damon_new_ctx(void)
  450. {
  451. struct damon_ctx *ctx;
  452. ctx = kzalloc_obj(*ctx);
  453. if (!ctx)
  454. return NULL;
  455. init_completion(&ctx->kdamond_started);
  456. ctx->attrs.sample_interval = 5 * 1000;
  457. ctx->attrs.aggr_interval = 100 * 1000;
  458. ctx->attrs.ops_update_interval = 60 * 1000 * 1000;
  459. ctx->passed_sample_intervals = 0;
  460. /* These will be set from kdamond_init_ctx() */
  461. ctx->next_aggregation_sis = 0;
  462. ctx->next_ops_update_sis = 0;
  463. mutex_init(&ctx->kdamond_lock);
  464. INIT_LIST_HEAD(&ctx->call_controls);
  465. mutex_init(&ctx->call_controls_lock);
  466. mutex_init(&ctx->walk_control_lock);
  467. ctx->attrs.min_nr_regions = 10;
  468. ctx->attrs.max_nr_regions = 1000;
  469. ctx->addr_unit = 1;
  470. ctx->min_region_sz = DAMON_MIN_REGION_SZ;
  471. INIT_LIST_HEAD(&ctx->adaptive_targets);
  472. INIT_LIST_HEAD(&ctx->schemes);
  473. return ctx;
  474. }
  475. static void damon_destroy_targets(struct damon_ctx *ctx)
  476. {
  477. struct damon_target *t, *next_t;
  478. damon_for_each_target_safe(t, next_t, ctx)
  479. damon_destroy_target(t, ctx);
  480. }
  481. void damon_destroy_ctx(struct damon_ctx *ctx)
  482. {
  483. struct damos *s, *next_s;
  484. damon_destroy_targets(ctx);
  485. damon_for_each_scheme_safe(s, next_s, ctx)
  486. damon_destroy_scheme(s);
  487. kfree(ctx);
  488. }
  489. static bool damon_attrs_equals(const struct damon_attrs *attrs1,
  490. const struct damon_attrs *attrs2)
  491. {
  492. const struct damon_intervals_goal *ig1 = &attrs1->intervals_goal;
  493. const struct damon_intervals_goal *ig2 = &attrs2->intervals_goal;
  494. return attrs1->sample_interval == attrs2->sample_interval &&
  495. attrs1->aggr_interval == attrs2->aggr_interval &&
  496. attrs1->ops_update_interval == attrs2->ops_update_interval &&
  497. attrs1->min_nr_regions == attrs2->min_nr_regions &&
  498. attrs1->max_nr_regions == attrs2->max_nr_regions &&
  499. ig1->access_bp == ig2->access_bp &&
  500. ig1->aggrs == ig2->aggrs &&
  501. ig1->min_sample_us == ig2->min_sample_us &&
  502. ig1->max_sample_us == ig2->max_sample_us;
  503. }
  504. static unsigned int damon_age_for_new_attrs(unsigned int age,
  505. struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
  506. {
  507. return age * old_attrs->aggr_interval / new_attrs->aggr_interval;
  508. }
  509. /* convert access ratio in bp (per 10,000) to nr_accesses */
  510. static unsigned int damon_accesses_bp_to_nr_accesses(
  511. unsigned int accesses_bp, struct damon_attrs *attrs)
  512. {
  513. return accesses_bp * damon_max_nr_accesses(attrs) / 10000;
  514. }
  515. /*
  516. * Convert nr_accesses to access ratio in bp (per 10,000).
  517. *
  518. * Callers should ensure attrs.aggr_interval is not zero, like
  519. * damon_update_monitoring_results() does . Otherwise, divide-by-zero would
  520. * happen.
  521. */
  522. static unsigned int damon_nr_accesses_to_accesses_bp(
  523. unsigned int nr_accesses, struct damon_attrs *attrs)
  524. {
  525. return nr_accesses * 10000 / damon_max_nr_accesses(attrs);
  526. }
  527. static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses,
  528. struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
  529. {
  530. return damon_accesses_bp_to_nr_accesses(
  531. damon_nr_accesses_to_accesses_bp(
  532. nr_accesses, old_attrs),
  533. new_attrs);
  534. }
  535. static void damon_update_monitoring_result(struct damon_region *r,
  536. struct damon_attrs *old_attrs, struct damon_attrs *new_attrs,
  537. bool aggregating)
  538. {
  539. if (!aggregating) {
  540. r->nr_accesses = damon_nr_accesses_for_new_attrs(
  541. r->nr_accesses, old_attrs, new_attrs);
  542. r->nr_accesses_bp = r->nr_accesses * 10000;
  543. } else {
  544. /*
  545. * if this is called in the middle of the aggregation, reset
  546. * the aggregations we made so far for this aggregation
  547. * interval. In other words, make the status like
  548. * kdamond_reset_aggregated() is called.
  549. */
  550. r->last_nr_accesses = damon_nr_accesses_for_new_attrs(
  551. r->last_nr_accesses, old_attrs, new_attrs);
  552. r->nr_accesses_bp = r->last_nr_accesses * 10000;
  553. r->nr_accesses = 0;
  554. }
  555. r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs);
  556. }
  557. /*
  558. * region->nr_accesses is the number of sampling intervals in the last
  559. * aggregation interval that access to the region has found, and region->age is
  560. * the number of aggregation intervals that its access pattern has maintained.
  561. * For the reason, the real meaning of the two fields depend on current
  562. * sampling interval and aggregation interval. This function updates
  563. * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs.
  564. */
  565. static void damon_update_monitoring_results(struct damon_ctx *ctx,
  566. struct damon_attrs *new_attrs, bool aggregating)
  567. {
  568. struct damon_attrs *old_attrs = &ctx->attrs;
  569. struct damon_target *t;
  570. struct damon_region *r;
  571. /* if any interval is zero, simply forgive conversion */
  572. if (!old_attrs->sample_interval || !old_attrs->aggr_interval ||
  573. !new_attrs->sample_interval ||
  574. !new_attrs->aggr_interval)
  575. return;
  576. damon_for_each_target(t, ctx)
  577. damon_for_each_region(r, t)
  578. damon_update_monitoring_result(
  579. r, old_attrs, new_attrs, aggregating);
  580. }
  581. /*
  582. * damon_valid_intervals_goal() - return if the intervals goal of @attrs is
  583. * valid.
  584. */
  585. static bool damon_valid_intervals_goal(struct damon_attrs *attrs)
  586. {
  587. struct damon_intervals_goal *goal = &attrs->intervals_goal;
  588. /* tuning is disabled */
  589. if (!goal->aggrs)
  590. return true;
  591. if (goal->min_sample_us > goal->max_sample_us)
  592. return false;
  593. if (attrs->sample_interval < goal->min_sample_us ||
  594. goal->max_sample_us < attrs->sample_interval)
  595. return false;
  596. return true;
  597. }
  598. /**
  599. * damon_set_attrs() - Set attributes for the monitoring.
  600. * @ctx: monitoring context
  601. * @attrs: monitoring attributes
  602. *
  603. * This function should be called while the kdamond is not running, an access
  604. * check results aggregation is not ongoing (e.g., from damon_call().
  605. *
  606. * Every time interval is in micro-seconds.
  607. *
  608. * Return: 0 on success, negative error code otherwise.
  609. */
  610. int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
  611. {
  612. unsigned long sample_interval = attrs->sample_interval ?
  613. attrs->sample_interval : 1;
  614. struct damos *s;
  615. bool aggregating = ctx->passed_sample_intervals <
  616. ctx->next_aggregation_sis;
  617. if (!damon_valid_intervals_goal(attrs))
  618. return -EINVAL;
  619. if (attrs->min_nr_regions < 3)
  620. return -EINVAL;
  621. if (attrs->min_nr_regions > attrs->max_nr_regions)
  622. return -EINVAL;
  623. if (attrs->sample_interval > attrs->aggr_interval)
  624. return -EINVAL;
  625. /* calls from core-external doesn't set this. */
  626. if (!attrs->aggr_samples)
  627. attrs->aggr_samples = attrs->aggr_interval / sample_interval;
  628. ctx->next_aggregation_sis = ctx->passed_sample_intervals +
  629. attrs->aggr_interval / sample_interval;
  630. ctx->next_ops_update_sis = ctx->passed_sample_intervals +
  631. attrs->ops_update_interval / sample_interval;
  632. damon_update_monitoring_results(ctx, attrs, aggregating);
  633. ctx->attrs = *attrs;
  634. damon_for_each_scheme(s, ctx)
  635. damos_set_next_apply_sis(s, ctx);
  636. return 0;
  637. }
  638. /**
  639. * damon_set_schemes() - Set data access monitoring based operation schemes.
  640. * @ctx: monitoring context
  641. * @schemes: array of the schemes
  642. * @nr_schemes: number of entries in @schemes
  643. *
  644. * This function should not be called while the kdamond of the context is
  645. * running.
  646. */
  647. void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes,
  648. ssize_t nr_schemes)
  649. {
  650. struct damos *s, *next;
  651. ssize_t i;
  652. damon_for_each_scheme_safe(s, next, ctx)
  653. damon_destroy_scheme(s);
  654. for (i = 0; i < nr_schemes; i++)
  655. damon_add_scheme(ctx, schemes[i]);
  656. }
  657. static struct damos_quota_goal *damos_nth_quota_goal(
  658. int n, struct damos_quota *q)
  659. {
  660. struct damos_quota_goal *goal;
  661. int i = 0;
  662. damos_for_each_quota_goal(goal, q) {
  663. if (i++ == n)
  664. return goal;
  665. }
  666. return NULL;
  667. }
  668. static void damos_commit_quota_goal_union(
  669. struct damos_quota_goal *dst, struct damos_quota_goal *src)
  670. {
  671. switch (dst->metric) {
  672. case DAMOS_QUOTA_NODE_MEM_USED_BP:
  673. case DAMOS_QUOTA_NODE_MEM_FREE_BP:
  674. dst->nid = src->nid;
  675. break;
  676. case DAMOS_QUOTA_NODE_MEMCG_USED_BP:
  677. case DAMOS_QUOTA_NODE_MEMCG_FREE_BP:
  678. dst->nid = src->nid;
  679. dst->memcg_id = src->memcg_id;
  680. break;
  681. default:
  682. break;
  683. }
  684. }
  685. static void damos_commit_quota_goal(
  686. struct damos_quota_goal *dst, struct damos_quota_goal *src)
  687. {
  688. dst->metric = src->metric;
  689. dst->target_value = src->target_value;
  690. if (dst->metric == DAMOS_QUOTA_USER_INPUT)
  691. dst->current_value = src->current_value;
  692. /* keep last_psi_total as is, since it will be updated in next cycle */
  693. damos_commit_quota_goal_union(dst, src);
  694. }
  695. /**
  696. * damos_commit_quota_goals() - Commit DAMOS quota goals to another quota.
  697. * @dst: The commit destination DAMOS quota.
  698. * @src: The commit source DAMOS quota.
  699. *
  700. * Copies user-specified parameters for quota goals from @src to @dst. Users
  701. * should use this function for quota goals-level parameters update of running
  702. * DAMON contexts, instead of manual in-place updates.
  703. *
  704. * This function should be called from parameters-update safe context, like
  705. * damon_call().
  706. */
  707. int damos_commit_quota_goals(struct damos_quota *dst, struct damos_quota *src)
  708. {
  709. struct damos_quota_goal *dst_goal, *next, *src_goal, *new_goal;
  710. int i = 0, j = 0;
  711. damos_for_each_quota_goal_safe(dst_goal, next, dst) {
  712. src_goal = damos_nth_quota_goal(i++, src);
  713. if (src_goal)
  714. damos_commit_quota_goal(dst_goal, src_goal);
  715. else
  716. damos_destroy_quota_goal(dst_goal);
  717. }
  718. damos_for_each_quota_goal_safe(src_goal, next, src) {
  719. if (j++ < i)
  720. continue;
  721. new_goal = damos_new_quota_goal(
  722. src_goal->metric, src_goal->target_value);
  723. if (!new_goal)
  724. return -ENOMEM;
  725. damos_commit_quota_goal(new_goal, src_goal);
  726. damos_add_quota_goal(dst, new_goal);
  727. }
  728. return 0;
  729. }
  730. static int damos_commit_quota(struct damos_quota *dst, struct damos_quota *src)
  731. {
  732. int err;
  733. dst->reset_interval = src->reset_interval;
  734. dst->ms = src->ms;
  735. dst->sz = src->sz;
  736. err = damos_commit_quota_goals(dst, src);
  737. if (err)
  738. return err;
  739. dst->weight_sz = src->weight_sz;
  740. dst->weight_nr_accesses = src->weight_nr_accesses;
  741. dst->weight_age = src->weight_age;
  742. return 0;
  743. }
  744. static struct damos_filter *damos_nth_core_filter(int n, struct damos *s)
  745. {
  746. struct damos_filter *filter;
  747. int i = 0;
  748. damos_for_each_core_filter(filter, s) {
  749. if (i++ == n)
  750. return filter;
  751. }
  752. return NULL;
  753. }
  754. static struct damos_filter *damos_nth_ops_filter(int n, struct damos *s)
  755. {
  756. struct damos_filter *filter;
  757. int i = 0;
  758. damos_for_each_ops_filter(filter, s) {
  759. if (i++ == n)
  760. return filter;
  761. }
  762. return NULL;
  763. }
  764. static void damos_commit_filter_arg(
  765. struct damos_filter *dst, struct damos_filter *src)
  766. {
  767. switch (dst->type) {
  768. case DAMOS_FILTER_TYPE_MEMCG:
  769. dst->memcg_id = src->memcg_id;
  770. break;
  771. case DAMOS_FILTER_TYPE_ADDR:
  772. dst->addr_range = src->addr_range;
  773. break;
  774. case DAMOS_FILTER_TYPE_TARGET:
  775. dst->target_idx = src->target_idx;
  776. break;
  777. case DAMOS_FILTER_TYPE_HUGEPAGE_SIZE:
  778. dst->sz_range = src->sz_range;
  779. break;
  780. default:
  781. break;
  782. }
  783. }
  784. static void damos_commit_filter(
  785. struct damos_filter *dst, struct damos_filter *src)
  786. {
  787. dst->type = src->type;
  788. dst->matching = src->matching;
  789. dst->allow = src->allow;
  790. damos_commit_filter_arg(dst, src);
  791. }
  792. static int damos_commit_core_filters(struct damos *dst, struct damos *src)
  793. {
  794. struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
  795. int i = 0, j = 0;
  796. damos_for_each_core_filter_safe(dst_filter, next, dst) {
  797. src_filter = damos_nth_core_filter(i++, src);
  798. if (src_filter)
  799. damos_commit_filter(dst_filter, src_filter);
  800. else
  801. damos_destroy_filter(dst_filter);
  802. }
  803. damos_for_each_core_filter_safe(src_filter, next, src) {
  804. if (j++ < i)
  805. continue;
  806. new_filter = damos_new_filter(
  807. src_filter->type, src_filter->matching,
  808. src_filter->allow);
  809. if (!new_filter)
  810. return -ENOMEM;
  811. damos_commit_filter_arg(new_filter, src_filter);
  812. damos_add_filter(dst, new_filter);
  813. }
  814. return 0;
  815. }
  816. static int damos_commit_ops_filters(struct damos *dst, struct damos *src)
  817. {
  818. struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
  819. int i = 0, j = 0;
  820. damos_for_each_ops_filter_safe(dst_filter, next, dst) {
  821. src_filter = damos_nth_ops_filter(i++, src);
  822. if (src_filter)
  823. damos_commit_filter(dst_filter, src_filter);
  824. else
  825. damos_destroy_filter(dst_filter);
  826. }
  827. damos_for_each_ops_filter_safe(src_filter, next, src) {
  828. if (j++ < i)
  829. continue;
  830. new_filter = damos_new_filter(
  831. src_filter->type, src_filter->matching,
  832. src_filter->allow);
  833. if (!new_filter)
  834. return -ENOMEM;
  835. damos_commit_filter_arg(new_filter, src_filter);
  836. damos_add_filter(dst, new_filter);
  837. }
  838. return 0;
  839. }
  840. /**
  841. * damos_filters_default_reject() - decide whether to reject memory that didn't
  842. * match with any given filter.
  843. * @filters: Given DAMOS filters of a group.
  844. */
  845. static bool damos_filters_default_reject(struct list_head *filters)
  846. {
  847. struct damos_filter *last_filter;
  848. if (list_empty(filters))
  849. return false;
  850. last_filter = list_last_entry(filters, struct damos_filter, list);
  851. return last_filter->allow;
  852. }
  853. static void damos_set_filters_default_reject(struct damos *s)
  854. {
  855. if (!list_empty(&s->ops_filters))
  856. s->core_filters_default_reject = false;
  857. else
  858. s->core_filters_default_reject =
  859. damos_filters_default_reject(&s->core_filters);
  860. s->ops_filters_default_reject =
  861. damos_filters_default_reject(&s->ops_filters);
  862. }
  863. static int damos_commit_dests(struct damos_migrate_dests *dst,
  864. struct damos_migrate_dests *src)
  865. {
  866. if (dst->nr_dests != src->nr_dests) {
  867. kfree(dst->node_id_arr);
  868. kfree(dst->weight_arr);
  869. dst->node_id_arr = kmalloc_array(src->nr_dests,
  870. sizeof(*dst->node_id_arr), GFP_KERNEL);
  871. if (!dst->node_id_arr) {
  872. dst->weight_arr = NULL;
  873. return -ENOMEM;
  874. }
  875. dst->weight_arr = kmalloc_array(src->nr_dests,
  876. sizeof(*dst->weight_arr), GFP_KERNEL);
  877. if (!dst->weight_arr) {
  878. /* ->node_id_arr will be freed by scheme destruction */
  879. return -ENOMEM;
  880. }
  881. }
  882. dst->nr_dests = src->nr_dests;
  883. for (int i = 0; i < src->nr_dests; i++) {
  884. dst->node_id_arr[i] = src->node_id_arr[i];
  885. dst->weight_arr[i] = src->weight_arr[i];
  886. }
  887. return 0;
  888. }
  889. static int damos_commit_filters(struct damos *dst, struct damos *src)
  890. {
  891. int err;
  892. err = damos_commit_core_filters(dst, src);
  893. if (err)
  894. return err;
  895. err = damos_commit_ops_filters(dst, src);
  896. if (err)
  897. return err;
  898. damos_set_filters_default_reject(dst);
  899. return 0;
  900. }
  901. static struct damos *damon_nth_scheme(int n, struct damon_ctx *ctx)
  902. {
  903. struct damos *s;
  904. int i = 0;
  905. damon_for_each_scheme(s, ctx) {
  906. if (i++ == n)
  907. return s;
  908. }
  909. return NULL;
  910. }
  911. static int damos_commit(struct damos *dst, struct damos *src)
  912. {
  913. int err;
  914. dst->pattern = src->pattern;
  915. dst->action = src->action;
  916. dst->apply_interval_us = src->apply_interval_us;
  917. err = damos_commit_quota(&dst->quota, &src->quota);
  918. if (err)
  919. return err;
  920. dst->wmarks = src->wmarks;
  921. dst->target_nid = src->target_nid;
  922. err = damos_commit_dests(&dst->migrate_dests, &src->migrate_dests);
  923. if (err)
  924. return err;
  925. err = damos_commit_filters(dst, src);
  926. if (err)
  927. return err;
  928. dst->max_nr_snapshots = src->max_nr_snapshots;
  929. return 0;
  930. }
  931. static int damon_commit_schemes(struct damon_ctx *dst, struct damon_ctx *src)
  932. {
  933. struct damos *dst_scheme, *next, *src_scheme, *new_scheme;
  934. int i = 0, j = 0, err;
  935. damon_for_each_scheme_safe(dst_scheme, next, dst) {
  936. src_scheme = damon_nth_scheme(i++, src);
  937. if (src_scheme) {
  938. err = damos_commit(dst_scheme, src_scheme);
  939. if (err)
  940. return err;
  941. } else {
  942. damon_destroy_scheme(dst_scheme);
  943. }
  944. }
  945. damon_for_each_scheme_safe(src_scheme, next, src) {
  946. if (j++ < i)
  947. continue;
  948. new_scheme = damon_new_scheme(&src_scheme->pattern,
  949. src_scheme->action,
  950. src_scheme->apply_interval_us,
  951. &src_scheme->quota, &src_scheme->wmarks,
  952. NUMA_NO_NODE);
  953. if (!new_scheme)
  954. return -ENOMEM;
  955. err = damos_commit(new_scheme, src_scheme);
  956. if (err) {
  957. damon_destroy_scheme(new_scheme);
  958. return err;
  959. }
  960. damon_add_scheme(dst, new_scheme);
  961. }
  962. return 0;
  963. }
  964. static struct damon_target *damon_nth_target(int n, struct damon_ctx *ctx)
  965. {
  966. struct damon_target *t;
  967. int i = 0;
  968. damon_for_each_target(t, ctx) {
  969. if (i++ == n)
  970. return t;
  971. }
  972. return NULL;
  973. }
  974. /*
  975. * The caller should ensure the regions of @src are
  976. * 1. valid (end >= src) and
  977. * 2. sorted by starting address.
  978. *
  979. * If @src has no region, @dst keeps current regions.
  980. */
  981. static int damon_commit_target_regions(struct damon_target *dst,
  982. struct damon_target *src, unsigned long src_min_region_sz)
  983. {
  984. struct damon_region *src_region;
  985. struct damon_addr_range *ranges;
  986. int i = 0, err;
  987. damon_for_each_region(src_region, src)
  988. i++;
  989. if (!i)
  990. return 0;
  991. ranges = kmalloc_objs(*ranges, i, GFP_KERNEL | __GFP_NOWARN);
  992. if (!ranges)
  993. return -ENOMEM;
  994. i = 0;
  995. damon_for_each_region(src_region, src)
  996. ranges[i++] = src_region->ar;
  997. err = damon_set_regions(dst, ranges, i, src_min_region_sz);
  998. kfree(ranges);
  999. return err;
  1000. }
  1001. static int damon_commit_target(
  1002. struct damon_target *dst, bool dst_has_pid,
  1003. struct damon_target *src, bool src_has_pid,
  1004. unsigned long src_min_region_sz)
  1005. {
  1006. int err;
  1007. err = damon_commit_target_regions(dst, src, src_min_region_sz);
  1008. if (err)
  1009. return err;
  1010. if (dst_has_pid)
  1011. put_pid(dst->pid);
  1012. if (src_has_pid)
  1013. get_pid(src->pid);
  1014. dst->pid = src->pid;
  1015. return 0;
  1016. }
  1017. static int damon_commit_targets(
  1018. struct damon_ctx *dst, struct damon_ctx *src)
  1019. {
  1020. struct damon_target *dst_target, *next, *src_target, *new_target;
  1021. int i = 0, j = 0, err;
  1022. damon_for_each_target_safe(dst_target, next, dst) {
  1023. src_target = damon_nth_target(i++, src);
  1024. /*
  1025. * If src target is obsolete, do not commit the parameters to
  1026. * the dst target, and further remove the dst target.
  1027. */
  1028. if (src_target && !src_target->obsolete) {
  1029. err = damon_commit_target(
  1030. dst_target, damon_target_has_pid(dst),
  1031. src_target, damon_target_has_pid(src),
  1032. src->min_region_sz);
  1033. if (err)
  1034. return err;
  1035. } else {
  1036. struct damos *s;
  1037. damon_destroy_target(dst_target, dst);
  1038. damon_for_each_scheme(s, dst) {
  1039. if (s->quota.charge_target_from == dst_target) {
  1040. s->quota.charge_target_from = NULL;
  1041. s->quota.charge_addr_from = 0;
  1042. }
  1043. }
  1044. }
  1045. }
  1046. damon_for_each_target_safe(src_target, next, src) {
  1047. if (j++ < i)
  1048. continue;
  1049. /* target to remove has no matching dst */
  1050. if (src_target->obsolete)
  1051. return -EINVAL;
  1052. new_target = damon_new_target();
  1053. if (!new_target)
  1054. return -ENOMEM;
  1055. err = damon_commit_target(new_target, false,
  1056. src_target, damon_target_has_pid(src),
  1057. src->min_region_sz);
  1058. if (err) {
  1059. damon_destroy_target(new_target, NULL);
  1060. return err;
  1061. }
  1062. damon_add_target(dst, new_target);
  1063. }
  1064. return 0;
  1065. }
  1066. /**
  1067. * damon_commit_ctx() - Commit parameters of a DAMON context to another.
  1068. * @dst: The commit destination DAMON context.
  1069. * @src: The commit source DAMON context.
  1070. *
  1071. * This function copies user-specified parameters from @src to @dst and update
  1072. * the internal status and results accordingly. Users should use this function
  1073. * for context-level parameters update of running context, instead of manual
  1074. * in-place updates.
  1075. *
  1076. * This function should be called from parameters-update safe context, like
  1077. * damon_call().
  1078. */
  1079. int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
  1080. {
  1081. int err;
  1082. dst->maybe_corrupted = true;
  1083. if (!is_power_of_2(src->min_region_sz))
  1084. return -EINVAL;
  1085. err = damon_commit_schemes(dst, src);
  1086. if (err)
  1087. return err;
  1088. err = damon_commit_targets(dst, src);
  1089. if (err)
  1090. return err;
  1091. /*
  1092. * schemes and targets should be updated first, since
  1093. * 1. damon_set_attrs() updates monitoring results of targets and
  1094. * next_apply_sis of schemes, and
  1095. * 2. ops update should be done after pid handling is done (target
  1096. * committing require putting pids).
  1097. */
  1098. if (!damon_attrs_equals(&dst->attrs, &src->attrs)) {
  1099. err = damon_set_attrs(dst, &src->attrs);
  1100. if (err)
  1101. return err;
  1102. }
  1103. dst->ops = src->ops;
  1104. dst->addr_unit = src->addr_unit;
  1105. dst->min_region_sz = src->min_region_sz;
  1106. dst->maybe_corrupted = false;
  1107. return 0;
  1108. }
  1109. /**
  1110. * damon_nr_running_ctxs() - Return number of currently running contexts.
  1111. */
  1112. int damon_nr_running_ctxs(void)
  1113. {
  1114. int nr_ctxs;
  1115. mutex_lock(&damon_lock);
  1116. nr_ctxs = nr_running_ctxs;
  1117. mutex_unlock(&damon_lock);
  1118. return nr_ctxs;
  1119. }
  1120. /* Returns the size upper limit for each monitoring region */
  1121. static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
  1122. {
  1123. struct damon_target *t;
  1124. struct damon_region *r;
  1125. unsigned long sz = 0;
  1126. damon_for_each_target(t, ctx) {
  1127. damon_for_each_region(r, t)
  1128. sz += damon_sz_region(r);
  1129. }
  1130. if (ctx->attrs.min_nr_regions)
  1131. sz /= ctx->attrs.min_nr_regions;
  1132. if (sz < ctx->min_region_sz)
  1133. sz = ctx->min_region_sz;
  1134. return sz;
  1135. }
  1136. static int kdamond_fn(void *data);
  1137. /*
  1138. * __damon_start() - Starts monitoring with given context.
  1139. * @ctx: monitoring context
  1140. *
  1141. * This function should be called while damon_lock is hold.
  1142. *
  1143. * Return: 0 on success, negative error code otherwise.
  1144. */
  1145. static int __damon_start(struct damon_ctx *ctx)
  1146. {
  1147. int err = -EBUSY;
  1148. mutex_lock(&ctx->kdamond_lock);
  1149. if (!ctx->kdamond) {
  1150. err = 0;
  1151. reinit_completion(&ctx->kdamond_started);
  1152. ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
  1153. nr_running_ctxs);
  1154. if (IS_ERR(ctx->kdamond)) {
  1155. err = PTR_ERR(ctx->kdamond);
  1156. ctx->kdamond = NULL;
  1157. } else {
  1158. wait_for_completion(&ctx->kdamond_started);
  1159. }
  1160. }
  1161. mutex_unlock(&ctx->kdamond_lock);
  1162. return err;
  1163. }
  1164. /**
  1165. * damon_start() - Starts the monitorings for a given group of contexts.
  1166. * @ctxs: an array of the pointers for contexts to start monitoring
  1167. * @nr_ctxs: size of @ctxs
  1168. * @exclusive: exclusiveness of this contexts group
  1169. *
  1170. * This function starts a group of monitoring threads for a group of monitoring
  1171. * contexts. One thread per each context is created and run in parallel. The
  1172. * caller should handle synchronization between the threads by itself. If
  1173. * @exclusive is true and a group of threads that created by other
  1174. * 'damon_start()' call is currently running, this function does nothing but
  1175. * returns -EBUSY.
  1176. *
  1177. * Return: 0 on success, negative error code otherwise.
  1178. */
  1179. int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
  1180. {
  1181. int i;
  1182. int err = 0;
  1183. mutex_lock(&damon_lock);
  1184. if ((exclusive && nr_running_ctxs) ||
  1185. (!exclusive && running_exclusive_ctxs)) {
  1186. mutex_unlock(&damon_lock);
  1187. return -EBUSY;
  1188. }
  1189. for (i = 0; i < nr_ctxs; i++) {
  1190. err = __damon_start(ctxs[i]);
  1191. if (err)
  1192. break;
  1193. nr_running_ctxs++;
  1194. }
  1195. if (exclusive && nr_running_ctxs)
  1196. running_exclusive_ctxs = true;
  1197. mutex_unlock(&damon_lock);
  1198. return err;
  1199. }
  1200. /*
  1201. * __damon_stop() - Stops monitoring of a given context.
  1202. * @ctx: monitoring context
  1203. *
  1204. * Return: 0 on success, negative error code otherwise.
  1205. */
  1206. static int __damon_stop(struct damon_ctx *ctx)
  1207. {
  1208. struct task_struct *tsk;
  1209. mutex_lock(&ctx->kdamond_lock);
  1210. tsk = ctx->kdamond;
  1211. if (tsk) {
  1212. get_task_struct(tsk);
  1213. mutex_unlock(&ctx->kdamond_lock);
  1214. kthread_stop_put(tsk);
  1215. return 0;
  1216. }
  1217. mutex_unlock(&ctx->kdamond_lock);
  1218. return -EPERM;
  1219. }
  1220. /**
  1221. * damon_stop() - Stops the monitorings for a given group of contexts.
  1222. * @ctxs: an array of the pointers for contexts to stop monitoring
  1223. * @nr_ctxs: size of @ctxs
  1224. *
  1225. * Return: 0 on success, negative error code otherwise.
  1226. */
  1227. int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
  1228. {
  1229. int i, err = 0;
  1230. for (i = 0; i < nr_ctxs; i++) {
  1231. /* nr_running_ctxs is decremented in kdamond_fn */
  1232. err = __damon_stop(ctxs[i]);
  1233. if (err)
  1234. break;
  1235. }
  1236. return err;
  1237. }
  1238. /**
  1239. * damon_is_running() - Returns if a given DAMON context is running.
  1240. * @ctx: The DAMON context to see if running.
  1241. *
  1242. * Return: true if @ctx is running, false otherwise.
  1243. */
  1244. bool damon_is_running(struct damon_ctx *ctx)
  1245. {
  1246. bool running;
  1247. mutex_lock(&ctx->kdamond_lock);
  1248. running = ctx->kdamond != NULL;
  1249. mutex_unlock(&ctx->kdamond_lock);
  1250. return running;
  1251. }
  1252. /**
  1253. * damon_kdamond_pid() - Return pid of a given DAMON context's worker thread.
  1254. * @ctx: The DAMON context of the question.
  1255. *
  1256. * Return: pid if @ctx is running, negative error code otherwise.
  1257. */
  1258. int damon_kdamond_pid(struct damon_ctx *ctx)
  1259. {
  1260. int pid = -EINVAL;
  1261. mutex_lock(&ctx->kdamond_lock);
  1262. if (ctx->kdamond)
  1263. pid = ctx->kdamond->pid;
  1264. mutex_unlock(&ctx->kdamond_lock);
  1265. return pid;
  1266. }
  1267. /*
  1268. * damon_call_handle_inactive_ctx() - handle DAMON call request that added to
  1269. * an inactive context.
  1270. * @ctx: The inactive DAMON context.
  1271. * @control: Control variable of the call request.
  1272. *
  1273. * This function is called in a case that @control is added to @ctx but @ctx is
  1274. * not running (inactive). See if @ctx handled @control or not, and cleanup
  1275. * @control if it was not handled.
  1276. *
  1277. * Returns 0 if @control was handled by @ctx, negative error code otherwise.
  1278. */
  1279. static int damon_call_handle_inactive_ctx(
  1280. struct damon_ctx *ctx, struct damon_call_control *control)
  1281. {
  1282. struct damon_call_control *c;
  1283. mutex_lock(&ctx->call_controls_lock);
  1284. list_for_each_entry(c, &ctx->call_controls, list) {
  1285. if (c == control) {
  1286. list_del(&control->list);
  1287. mutex_unlock(&ctx->call_controls_lock);
  1288. return -EINVAL;
  1289. }
  1290. }
  1291. mutex_unlock(&ctx->call_controls_lock);
  1292. return 0;
  1293. }
  1294. /**
  1295. * damon_call() - Invoke a given function on DAMON worker thread (kdamond).
  1296. * @ctx: DAMON context to call the function for.
  1297. * @control: Control variable of the call request.
  1298. *
  1299. * Ask DAMON worker thread (kdamond) of @ctx to call a function with an
  1300. * argument data that respectively passed via &damon_call_control->fn and
  1301. * &damon_call_control->data of @control. If &damon_call_control->repeat of
  1302. * @control is unset, further wait until the kdamond finishes handling of the
  1303. * request. Otherwise, return as soon as the request is made.
  1304. *
  1305. * The kdamond executes the function with the argument in the main loop, just
  1306. * after a sampling of the iteration is finished. The function can hence
  1307. * safely access the internal data of the &struct damon_ctx without additional
  1308. * synchronization. The return value of the function will be saved in
  1309. * &damon_call_control->return_code.
  1310. *
  1311. * Return: 0 on success, negative error code otherwise.
  1312. */
  1313. int damon_call(struct damon_ctx *ctx, struct damon_call_control *control)
  1314. {
  1315. if (!control->repeat)
  1316. init_completion(&control->completion);
  1317. control->canceled = false;
  1318. INIT_LIST_HEAD(&control->list);
  1319. mutex_lock(&ctx->call_controls_lock);
  1320. list_add_tail(&control->list, &ctx->call_controls);
  1321. mutex_unlock(&ctx->call_controls_lock);
  1322. if (!damon_is_running(ctx))
  1323. return damon_call_handle_inactive_ctx(ctx, control);
  1324. if (control->repeat)
  1325. return 0;
  1326. wait_for_completion(&control->completion);
  1327. if (control->canceled)
  1328. return -ECANCELED;
  1329. return 0;
  1330. }
  1331. /**
  1332. * damos_walk() - Invoke a given functions while DAMOS walk regions.
  1333. * @ctx: DAMON context to call the functions for.
  1334. * @control: Control variable of the walk request.
  1335. *
  1336. * Ask DAMON worker thread (kdamond) of @ctx to call a function for each region
  1337. * that the kdamond will apply DAMOS action to, and wait until the kdamond
  1338. * finishes handling of the request.
  1339. *
  1340. * The kdamond executes the given function in the main loop, for each region
  1341. * just after it applied any DAMOS actions of @ctx to it. The invocation is
  1342. * made only within one &damos->apply_interval_us since damos_walk()
  1343. * invocation, for each scheme. The given callback function can hence safely
  1344. * access the internal data of &struct damon_ctx and &struct damon_region that
  1345. * each of the scheme will apply the action for next interval, without
  1346. * additional synchronizations against the kdamond. If every scheme of @ctx
  1347. * passed at least one &damos->apply_interval_us, kdamond marks the request as
  1348. * completed so that damos_walk() can wakeup and return.
  1349. *
  1350. * Return: 0 on success, negative error code otherwise.
  1351. */
  1352. int damos_walk(struct damon_ctx *ctx, struct damos_walk_control *control)
  1353. {
  1354. init_completion(&control->completion);
  1355. control->canceled = false;
  1356. mutex_lock(&ctx->walk_control_lock);
  1357. if (ctx->walk_control) {
  1358. mutex_unlock(&ctx->walk_control_lock);
  1359. return -EBUSY;
  1360. }
  1361. ctx->walk_control = control;
  1362. mutex_unlock(&ctx->walk_control_lock);
  1363. if (!damon_is_running(ctx)) {
  1364. mutex_lock(&ctx->walk_control_lock);
  1365. if (ctx->walk_control == control)
  1366. ctx->walk_control = NULL;
  1367. mutex_unlock(&ctx->walk_control_lock);
  1368. return -EINVAL;
  1369. }
  1370. wait_for_completion(&control->completion);
  1371. if (control->canceled)
  1372. return -ECANCELED;
  1373. return 0;
  1374. }
  1375. /*
  1376. * Warn and fix corrupted ->nr_accesses[_bp] for investigations and preventing
  1377. * the problem being propagated.
  1378. */
  1379. static void damon_warn_fix_nr_accesses_corruption(struct damon_region *r)
  1380. {
  1381. if (r->nr_accesses_bp == r->nr_accesses * 10000)
  1382. return;
  1383. WARN_ONCE(true, "invalid nr_accesses_bp at reset: %u %u\n",
  1384. r->nr_accesses_bp, r->nr_accesses);
  1385. r->nr_accesses_bp = r->nr_accesses * 10000;
  1386. }
  1387. /*
  1388. * Reset the aggregated monitoring results ('nr_accesses' of each region).
  1389. */
  1390. static void kdamond_reset_aggregated(struct damon_ctx *c)
  1391. {
  1392. struct damon_target *t;
  1393. unsigned int ti = 0; /* target's index */
  1394. damon_for_each_target(t, c) {
  1395. struct damon_region *r;
  1396. damon_for_each_region(r, t) {
  1397. trace_damon_aggregated(ti, r, damon_nr_regions(t));
  1398. damon_warn_fix_nr_accesses_corruption(r);
  1399. r->last_nr_accesses = r->nr_accesses;
  1400. r->nr_accesses = 0;
  1401. }
  1402. ti++;
  1403. }
  1404. }
  1405. static unsigned long damon_get_intervals_score(struct damon_ctx *c)
  1406. {
  1407. struct damon_target *t;
  1408. struct damon_region *r;
  1409. unsigned long sz_region, max_access_events = 0, access_events = 0;
  1410. unsigned long target_access_events;
  1411. unsigned long goal_bp = c->attrs.intervals_goal.access_bp;
  1412. damon_for_each_target(t, c) {
  1413. damon_for_each_region(r, t) {
  1414. sz_region = damon_sz_region(r);
  1415. max_access_events += sz_region * c->attrs.aggr_samples;
  1416. access_events += sz_region * r->nr_accesses;
  1417. }
  1418. }
  1419. target_access_events = max_access_events * goal_bp / 10000;
  1420. target_access_events = target_access_events ? : 1;
  1421. return access_events * 10000 / target_access_events;
  1422. }
  1423. static unsigned long damon_feed_loop_next_input(unsigned long last_input,
  1424. unsigned long score);
  1425. static unsigned long damon_get_intervals_adaptation_bp(struct damon_ctx *c)
  1426. {
  1427. unsigned long score_bp, adaptation_bp;
  1428. score_bp = damon_get_intervals_score(c);
  1429. adaptation_bp = damon_feed_loop_next_input(100000000, score_bp) /
  1430. 10000;
  1431. /*
  1432. * adaptation_bp ranges from 1 to 20,000. Avoid too rapid reduction of
  1433. * the intervals by rescaling [1,10,000] to [5000, 10,000].
  1434. */
  1435. if (adaptation_bp <= 10000)
  1436. adaptation_bp = 5000 + adaptation_bp / 2;
  1437. return adaptation_bp;
  1438. }
  1439. static void kdamond_tune_intervals(struct damon_ctx *c)
  1440. {
  1441. unsigned long adaptation_bp;
  1442. struct damon_attrs new_attrs;
  1443. struct damon_intervals_goal *goal;
  1444. adaptation_bp = damon_get_intervals_adaptation_bp(c);
  1445. if (adaptation_bp == 10000)
  1446. return;
  1447. new_attrs = c->attrs;
  1448. goal = &c->attrs.intervals_goal;
  1449. new_attrs.sample_interval = min(goal->max_sample_us,
  1450. c->attrs.sample_interval * adaptation_bp / 10000);
  1451. new_attrs.sample_interval = max(goal->min_sample_us,
  1452. new_attrs.sample_interval);
  1453. new_attrs.aggr_interval = new_attrs.sample_interval *
  1454. c->attrs.aggr_samples;
  1455. trace_damon_monitor_intervals_tune(new_attrs.sample_interval);
  1456. damon_set_attrs(c, &new_attrs);
  1457. }
  1458. static void damon_split_region_at(struct damon_target *t,
  1459. struct damon_region *r, unsigned long sz_r);
  1460. static bool __damos_valid_target(struct damon_region *r, struct damos *s)
  1461. {
  1462. unsigned long sz;
  1463. unsigned int nr_accesses = r->nr_accesses_bp / 10000;
  1464. sz = damon_sz_region(r);
  1465. return s->pattern.min_sz_region <= sz &&
  1466. sz <= s->pattern.max_sz_region &&
  1467. s->pattern.min_nr_accesses <= nr_accesses &&
  1468. nr_accesses <= s->pattern.max_nr_accesses &&
  1469. s->pattern.min_age_region <= r->age &&
  1470. r->age <= s->pattern.max_age_region;
  1471. }
  1472. static bool damos_valid_target(struct damon_ctx *c, struct damon_target *t,
  1473. struct damon_region *r, struct damos *s)
  1474. {
  1475. bool ret = __damos_valid_target(r, s);
  1476. if (!ret || !s->quota.esz || !c->ops.get_scheme_score)
  1477. return ret;
  1478. return c->ops.get_scheme_score(c, t, r, s) >= s->quota.min_score;
  1479. }
  1480. /*
  1481. * damos_skip_charged_region() - Check if the given region or starting part of
  1482. * it is already charged for the DAMOS quota.
  1483. * @t: The target of the region.
  1484. * @rp: The pointer to the region.
  1485. * @s: The scheme to be applied.
  1486. * @min_region_sz: minimum region size.
  1487. *
  1488. * If a quota of a scheme has exceeded in a quota charge window, the scheme's
  1489. * action would applied to only a part of the target access pattern fulfilling
  1490. * regions. To avoid applying the scheme action to only already applied
  1491. * regions, DAMON skips applying the scheme action to the regions that charged
  1492. * in the previous charge window.
  1493. *
  1494. * This function checks if a given region should be skipped or not for the
  1495. * reason. If only the starting part of the region has previously charged,
  1496. * this function splits the region into two so that the second one covers the
  1497. * area that not charged in the previous charge widnow and saves the second
  1498. * region in *rp and returns false, so that the caller can apply DAMON action
  1499. * to the second one.
  1500. *
  1501. * Return: true if the region should be entirely skipped, false otherwise.
  1502. */
  1503. static bool damos_skip_charged_region(struct damon_target *t,
  1504. struct damon_region **rp, struct damos *s,
  1505. unsigned long min_region_sz)
  1506. {
  1507. struct damon_region *r = *rp;
  1508. struct damos_quota *quota = &s->quota;
  1509. unsigned long sz_to_skip;
  1510. /* Skip previously charged regions */
  1511. if (quota->charge_target_from) {
  1512. if (t != quota->charge_target_from)
  1513. return true;
  1514. if (r == damon_last_region(t)) {
  1515. quota->charge_target_from = NULL;
  1516. quota->charge_addr_from = 0;
  1517. return true;
  1518. }
  1519. if (quota->charge_addr_from &&
  1520. r->ar.end <= quota->charge_addr_from)
  1521. return true;
  1522. if (quota->charge_addr_from && r->ar.start <
  1523. quota->charge_addr_from) {
  1524. sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
  1525. r->ar.start, min_region_sz);
  1526. if (!sz_to_skip) {
  1527. if (damon_sz_region(r) <= min_region_sz)
  1528. return true;
  1529. sz_to_skip = min_region_sz;
  1530. }
  1531. damon_split_region_at(t, r, sz_to_skip);
  1532. r = damon_next_region(r);
  1533. *rp = r;
  1534. }
  1535. quota->charge_target_from = NULL;
  1536. quota->charge_addr_from = 0;
  1537. }
  1538. return false;
  1539. }
  1540. static void damos_update_stat(struct damos *s,
  1541. unsigned long sz_tried, unsigned long sz_applied,
  1542. unsigned long sz_ops_filter_passed)
  1543. {
  1544. s->stat.nr_tried++;
  1545. s->stat.sz_tried += sz_tried;
  1546. if (sz_applied)
  1547. s->stat.nr_applied++;
  1548. s->stat.sz_applied += sz_applied;
  1549. s->stat.sz_ops_filter_passed += sz_ops_filter_passed;
  1550. }
  1551. static bool damos_filter_match(struct damon_ctx *ctx, struct damon_target *t,
  1552. struct damon_region *r, struct damos_filter *filter,
  1553. unsigned long min_region_sz)
  1554. {
  1555. bool matched = false;
  1556. struct damon_target *ti;
  1557. int target_idx = 0;
  1558. unsigned long start, end;
  1559. switch (filter->type) {
  1560. case DAMOS_FILTER_TYPE_TARGET:
  1561. damon_for_each_target(ti, ctx) {
  1562. if (ti == t)
  1563. break;
  1564. target_idx++;
  1565. }
  1566. matched = target_idx == filter->target_idx;
  1567. break;
  1568. case DAMOS_FILTER_TYPE_ADDR:
  1569. start = ALIGN_DOWN(filter->addr_range.start, min_region_sz);
  1570. end = ALIGN_DOWN(filter->addr_range.end, min_region_sz);
  1571. /* inside the range */
  1572. if (start <= r->ar.start && r->ar.end <= end) {
  1573. matched = true;
  1574. break;
  1575. }
  1576. /* outside of the range */
  1577. if (r->ar.end <= start || end <= r->ar.start) {
  1578. matched = false;
  1579. break;
  1580. }
  1581. /* start before the range and overlap */
  1582. if (r->ar.start < start) {
  1583. damon_split_region_at(t, r, start - r->ar.start);
  1584. matched = false;
  1585. break;
  1586. }
  1587. /* start inside the range */
  1588. damon_split_region_at(t, r, end - r->ar.start);
  1589. matched = true;
  1590. break;
  1591. default:
  1592. return false;
  1593. }
  1594. return matched == filter->matching;
  1595. }
  1596. static bool damos_core_filter_out(struct damon_ctx *ctx, struct damon_target *t,
  1597. struct damon_region *r, struct damos *s)
  1598. {
  1599. struct damos_filter *filter;
  1600. s->core_filters_allowed = false;
  1601. damos_for_each_core_filter(filter, s) {
  1602. if (damos_filter_match(ctx, t, r, filter, ctx->min_region_sz)) {
  1603. if (filter->allow)
  1604. s->core_filters_allowed = true;
  1605. return !filter->allow;
  1606. }
  1607. }
  1608. return s->core_filters_default_reject;
  1609. }
  1610. /*
  1611. * damos_walk_call_walk() - Call &damos_walk_control->walk_fn.
  1612. * @ctx: The context of &damon_ctx->walk_control.
  1613. * @t: The monitoring target of @r that @s will be applied.
  1614. * @r: The region of @t that @s will be applied.
  1615. * @s: The scheme of @ctx that will be applied to @r.
  1616. *
  1617. * This function is called from kdamond whenever it asked the operation set to
  1618. * apply a DAMOS scheme action to a region. If a DAMOS walk request is
  1619. * installed by damos_walk() and not yet uninstalled, invoke it.
  1620. */
  1621. static void damos_walk_call_walk(struct damon_ctx *ctx, struct damon_target *t,
  1622. struct damon_region *r, struct damos *s,
  1623. unsigned long sz_filter_passed)
  1624. {
  1625. struct damos_walk_control *control;
  1626. if (s->walk_completed)
  1627. return;
  1628. control = ctx->walk_control;
  1629. if (!control)
  1630. return;
  1631. control->walk_fn(control->data, ctx, t, r, s, sz_filter_passed);
  1632. }
  1633. /*
  1634. * damos_walk_complete() - Complete DAMOS walk request if all walks are done.
  1635. * @ctx: The context of &damon_ctx->walk_control.
  1636. * @s: A scheme of @ctx that all walks are now done.
  1637. *
  1638. * This function is called when kdamond finished applying the action of a DAMOS
  1639. * scheme to all regions that eligible for the given &damos->apply_interval_us.
  1640. * If every scheme of @ctx including @s now finished walking for at least one
  1641. * &damos->apply_interval_us, this function makrs the handling of the given
  1642. * DAMOS walk request is done, so that damos_walk() can wake up and return.
  1643. */
  1644. static void damos_walk_complete(struct damon_ctx *ctx, struct damos *s)
  1645. {
  1646. struct damos *siter;
  1647. struct damos_walk_control *control;
  1648. control = ctx->walk_control;
  1649. if (!control)
  1650. return;
  1651. s->walk_completed = true;
  1652. /* if all schemes completed, signal completion to walker */
  1653. damon_for_each_scheme(siter, ctx) {
  1654. if (!siter->walk_completed)
  1655. return;
  1656. }
  1657. damon_for_each_scheme(siter, ctx)
  1658. siter->walk_completed = false;
  1659. complete(&control->completion);
  1660. ctx->walk_control = NULL;
  1661. }
  1662. /*
  1663. * damos_walk_cancel() - Cancel the current DAMOS walk request.
  1664. * @ctx: The context of &damon_ctx->walk_control.
  1665. *
  1666. * This function is called when @ctx is deactivated by DAMOS watermarks, DAMOS
  1667. * walk is requested but there is no DAMOS scheme to walk for, or the kdamond
  1668. * is already out of the main loop and therefore gonna be terminated, and hence
  1669. * cannot continue the walks. This function therefore marks the walk request
  1670. * as canceled, so that damos_walk() can wake up and return.
  1671. */
  1672. static void damos_walk_cancel(struct damon_ctx *ctx)
  1673. {
  1674. struct damos_walk_control *control;
  1675. mutex_lock(&ctx->walk_control_lock);
  1676. control = ctx->walk_control;
  1677. mutex_unlock(&ctx->walk_control_lock);
  1678. if (!control)
  1679. return;
  1680. control->canceled = true;
  1681. complete(&control->completion);
  1682. mutex_lock(&ctx->walk_control_lock);
  1683. ctx->walk_control = NULL;
  1684. mutex_unlock(&ctx->walk_control_lock);
  1685. }
  1686. static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
  1687. struct damon_region *r, struct damos *s)
  1688. {
  1689. struct damos_quota *quota = &s->quota;
  1690. unsigned long sz = damon_sz_region(r);
  1691. struct timespec64 begin, end;
  1692. unsigned long sz_applied = 0;
  1693. unsigned long sz_ops_filter_passed = 0;
  1694. /*
  1695. * We plan to support multiple context per kdamond, as DAMON sysfs
  1696. * implies with 'nr_contexts' file. Nevertheless, only single context
  1697. * per kdamond is supported for now. So, we can simply use '0' context
  1698. * index here.
  1699. */
  1700. unsigned int cidx = 0;
  1701. struct damos *siter; /* schemes iterator */
  1702. unsigned int sidx = 0;
  1703. struct damon_target *titer; /* targets iterator */
  1704. unsigned int tidx = 0;
  1705. bool do_trace = false;
  1706. /* get indices for trace_damos_before_apply() */
  1707. if (trace_damos_before_apply_enabled()) {
  1708. damon_for_each_scheme(siter, c) {
  1709. if (siter == s)
  1710. break;
  1711. sidx++;
  1712. }
  1713. damon_for_each_target(titer, c) {
  1714. if (titer == t)
  1715. break;
  1716. tidx++;
  1717. }
  1718. do_trace = true;
  1719. }
  1720. if (c->ops.apply_scheme) {
  1721. if (quota->esz && quota->charged_sz + sz > quota->esz) {
  1722. sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
  1723. c->min_region_sz);
  1724. if (!sz)
  1725. goto update_stat;
  1726. damon_split_region_at(t, r, sz);
  1727. }
  1728. if (damos_core_filter_out(c, t, r, s))
  1729. return;
  1730. ktime_get_coarse_ts64(&begin);
  1731. trace_damos_before_apply(cidx, sidx, tidx, r,
  1732. damon_nr_regions(t), do_trace);
  1733. sz_applied = c->ops.apply_scheme(c, t, r, s,
  1734. &sz_ops_filter_passed);
  1735. damos_walk_call_walk(c, t, r, s, sz_ops_filter_passed);
  1736. ktime_get_coarse_ts64(&end);
  1737. quota->total_charged_ns += timespec64_to_ns(&end) -
  1738. timespec64_to_ns(&begin);
  1739. quota->charged_sz += sz;
  1740. if (quota->esz && quota->charged_sz >= quota->esz) {
  1741. quota->charge_target_from = t;
  1742. quota->charge_addr_from = r->ar.end + 1;
  1743. }
  1744. }
  1745. if (s->action != DAMOS_STAT)
  1746. r->age = 0;
  1747. update_stat:
  1748. damos_update_stat(s, sz, sz_applied, sz_ops_filter_passed);
  1749. }
  1750. static void damon_do_apply_schemes(struct damon_ctx *c,
  1751. struct damon_target *t,
  1752. struct damon_region *r)
  1753. {
  1754. struct damos *s;
  1755. damon_for_each_scheme(s, c) {
  1756. struct damos_quota *quota = &s->quota;
  1757. if (c->passed_sample_intervals < s->next_apply_sis)
  1758. continue;
  1759. if (!s->wmarks.activated)
  1760. continue;
  1761. /* Check the quota */
  1762. if (quota->esz && quota->charged_sz >= quota->esz)
  1763. continue;
  1764. if (damos_skip_charged_region(t, &r, s, c->min_region_sz))
  1765. continue;
  1766. if (s->max_nr_snapshots &&
  1767. s->max_nr_snapshots <= s->stat.nr_snapshots)
  1768. continue;
  1769. if (damos_valid_target(c, t, r, s))
  1770. damos_apply_scheme(c, t, r, s);
  1771. if (damon_is_last_region(r, t))
  1772. s->stat.nr_snapshots++;
  1773. }
  1774. }
  1775. /*
  1776. * damon_feed_loop_next_input() - get next input to achieve a target score.
  1777. * @last_input The last input.
  1778. * @score Current score that made with @last_input.
  1779. *
  1780. * Calculate next input to achieve the target score, based on the last input
  1781. * and current score. Assuming the input and the score are positively
  1782. * proportional, calculate how much compensation should be added to or
  1783. * subtracted from the last input as a proportion of the last input. Avoid
  1784. * next input always being zero by setting it non-zero always. In short form
  1785. * (assuming support of float and signed calculations), the algorithm is as
  1786. * below.
  1787. *
  1788. * next_input = max(last_input * ((goal - current) / goal + 1), 1)
  1789. *
  1790. * For simple implementation, we assume the target score is always 10,000. The
  1791. * caller should adjust @score for this.
  1792. *
  1793. * Returns next input that assumed to achieve the target score.
  1794. */
  1795. static unsigned long damon_feed_loop_next_input(unsigned long last_input,
  1796. unsigned long score)
  1797. {
  1798. const unsigned long goal = 10000;
  1799. /* Set minimum input as 10000 to avoid compensation be zero */
  1800. const unsigned long min_input = 10000;
  1801. unsigned long score_goal_diff, compensation;
  1802. bool over_achieving = score > goal;
  1803. if (score == goal)
  1804. return last_input;
  1805. if (score >= goal * 2)
  1806. return min_input;
  1807. if (over_achieving)
  1808. score_goal_diff = score - goal;
  1809. else
  1810. score_goal_diff = goal - score;
  1811. if (last_input < ULONG_MAX / score_goal_diff)
  1812. compensation = last_input * score_goal_diff / goal;
  1813. else
  1814. compensation = last_input / goal * score_goal_diff;
  1815. if (over_achieving)
  1816. return max(last_input - compensation, min_input);
  1817. if (last_input < ULONG_MAX - compensation)
  1818. return last_input + compensation;
  1819. return ULONG_MAX;
  1820. }
  1821. #ifdef CONFIG_PSI
  1822. static u64 damos_get_some_mem_psi_total(void)
  1823. {
  1824. if (static_branch_likely(&psi_disabled))
  1825. return 0;
  1826. return div_u64(psi_system.total[PSI_AVGS][PSI_MEM * 2],
  1827. NSEC_PER_USEC);
  1828. }
  1829. #else /* CONFIG_PSI */
  1830. static inline u64 damos_get_some_mem_psi_total(void)
  1831. {
  1832. return 0;
  1833. };
  1834. #endif /* CONFIG_PSI */
  1835. #ifdef CONFIG_NUMA
  1836. static __kernel_ulong_t damos_get_node_mem_bp(
  1837. struct damos_quota_goal *goal)
  1838. {
  1839. struct sysinfo i;
  1840. __kernel_ulong_t numerator;
  1841. si_meminfo_node(&i, goal->nid);
  1842. if (goal->metric == DAMOS_QUOTA_NODE_MEM_USED_BP)
  1843. numerator = i.totalram - i.freeram;
  1844. else /* DAMOS_QUOTA_NODE_MEM_FREE_BP */
  1845. numerator = i.freeram;
  1846. return numerator * 10000 / i.totalram;
  1847. }
  1848. static unsigned long damos_get_node_memcg_used_bp(
  1849. struct damos_quota_goal *goal)
  1850. {
  1851. struct mem_cgroup *memcg;
  1852. struct lruvec *lruvec;
  1853. unsigned long used_pages, numerator;
  1854. struct sysinfo i;
  1855. memcg = mem_cgroup_get_from_id(goal->memcg_id);
  1856. if (!memcg) {
  1857. if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
  1858. return 0;
  1859. else /* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
  1860. return 10000;
  1861. }
  1862. mem_cgroup_flush_stats(memcg);
  1863. lruvec = mem_cgroup_lruvec(memcg, NODE_DATA(goal->nid));
  1864. used_pages = lruvec_page_state(lruvec, NR_ACTIVE_ANON);
  1865. used_pages += lruvec_page_state(lruvec, NR_INACTIVE_ANON);
  1866. used_pages += lruvec_page_state(lruvec, NR_ACTIVE_FILE);
  1867. used_pages += lruvec_page_state(lruvec, NR_INACTIVE_FILE);
  1868. mem_cgroup_put(memcg);
  1869. si_meminfo_node(&i, goal->nid);
  1870. if (goal->metric == DAMOS_QUOTA_NODE_MEMCG_USED_BP)
  1871. numerator = used_pages;
  1872. else /* DAMOS_QUOTA_NODE_MEMCG_FREE_BP */
  1873. numerator = i.totalram - used_pages;
  1874. return numerator * 10000 / i.totalram;
  1875. }
  1876. #else
  1877. static __kernel_ulong_t damos_get_node_mem_bp(
  1878. struct damos_quota_goal *goal)
  1879. {
  1880. return 0;
  1881. }
  1882. static unsigned long damos_get_node_memcg_used_bp(
  1883. struct damos_quota_goal *goal)
  1884. {
  1885. return 0;
  1886. }
  1887. #endif
  1888. /*
  1889. * Returns LRU-active or inactive memory to total LRU memory size ratio.
  1890. */
  1891. static unsigned int damos_get_in_active_mem_bp(bool active_ratio)
  1892. {
  1893. unsigned long active, inactive, total;
  1894. /* This should align with /proc/meminfo output */
  1895. active = global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_ANON) +
  1896. global_node_page_state(NR_LRU_BASE + LRU_ACTIVE_FILE);
  1897. inactive = global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_ANON) +
  1898. global_node_page_state(NR_LRU_BASE + LRU_INACTIVE_FILE);
  1899. total = active + inactive;
  1900. if (active_ratio)
  1901. return active * 10000 / total;
  1902. return inactive * 10000 / total;
  1903. }
  1904. static void damos_set_quota_goal_current_value(struct damos_quota_goal *goal)
  1905. {
  1906. u64 now_psi_total;
  1907. switch (goal->metric) {
  1908. case DAMOS_QUOTA_USER_INPUT:
  1909. /* User should already set goal->current_value */
  1910. break;
  1911. case DAMOS_QUOTA_SOME_MEM_PSI_US:
  1912. now_psi_total = damos_get_some_mem_psi_total();
  1913. goal->current_value = now_psi_total - goal->last_psi_total;
  1914. goal->last_psi_total = now_psi_total;
  1915. break;
  1916. case DAMOS_QUOTA_NODE_MEM_USED_BP:
  1917. case DAMOS_QUOTA_NODE_MEM_FREE_BP:
  1918. goal->current_value = damos_get_node_mem_bp(goal);
  1919. break;
  1920. case DAMOS_QUOTA_NODE_MEMCG_USED_BP:
  1921. case DAMOS_QUOTA_NODE_MEMCG_FREE_BP:
  1922. goal->current_value = damos_get_node_memcg_used_bp(goal);
  1923. break;
  1924. case DAMOS_QUOTA_ACTIVE_MEM_BP:
  1925. case DAMOS_QUOTA_INACTIVE_MEM_BP:
  1926. goal->current_value = damos_get_in_active_mem_bp(
  1927. goal->metric == DAMOS_QUOTA_ACTIVE_MEM_BP);
  1928. break;
  1929. default:
  1930. break;
  1931. }
  1932. }
  1933. /* Return the highest score since it makes schemes least aggressive */
  1934. static unsigned long damos_quota_score(struct damos_quota *quota)
  1935. {
  1936. struct damos_quota_goal *goal;
  1937. unsigned long highest_score = 0;
  1938. damos_for_each_quota_goal(goal, quota) {
  1939. damos_set_quota_goal_current_value(goal);
  1940. highest_score = max(highest_score,
  1941. goal->current_value * 10000 /
  1942. goal->target_value);
  1943. }
  1944. return highest_score;
  1945. }
  1946. /*
  1947. * Called only if quota->ms, or quota->sz are set, or quota->goals is not empty
  1948. */
  1949. static void damos_set_effective_quota(struct damos_quota *quota)
  1950. {
  1951. unsigned long throughput;
  1952. unsigned long esz = ULONG_MAX;
  1953. if (!quota->ms && list_empty(&quota->goals)) {
  1954. quota->esz = quota->sz;
  1955. return;
  1956. }
  1957. if (!list_empty(&quota->goals)) {
  1958. unsigned long score = damos_quota_score(quota);
  1959. quota->esz_bp = damon_feed_loop_next_input(
  1960. max(quota->esz_bp, 10000UL),
  1961. score);
  1962. esz = quota->esz_bp / 10000;
  1963. }
  1964. if (quota->ms) {
  1965. if (quota->total_charged_ns)
  1966. throughput = mult_frac(quota->total_charged_sz, 1000000,
  1967. quota->total_charged_ns);
  1968. else
  1969. throughput = PAGE_SIZE * 1024;
  1970. esz = min(throughput * quota->ms, esz);
  1971. }
  1972. if (quota->sz && quota->sz < esz)
  1973. esz = quota->sz;
  1974. quota->esz = esz;
  1975. }
  1976. static void damos_trace_esz(struct damon_ctx *c, struct damos *s,
  1977. struct damos_quota *quota)
  1978. {
  1979. unsigned int cidx = 0, sidx = 0;
  1980. struct damos *siter;
  1981. damon_for_each_scheme(siter, c) {
  1982. if (siter == s)
  1983. break;
  1984. sidx++;
  1985. }
  1986. trace_damos_esz(cidx, sidx, quota->esz);
  1987. }
  1988. static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
  1989. {
  1990. struct damos_quota *quota = &s->quota;
  1991. struct damon_target *t;
  1992. struct damon_region *r;
  1993. unsigned long cumulated_sz, cached_esz;
  1994. unsigned int score, max_score = 0;
  1995. if (!quota->ms && !quota->sz && list_empty(&quota->goals))
  1996. return;
  1997. /* First charge window */
  1998. if (!quota->total_charged_sz && !quota->charged_from) {
  1999. quota->charged_from = jiffies;
  2000. damos_set_effective_quota(quota);
  2001. }
  2002. /* New charge window starts */
  2003. if (time_after_eq(jiffies, quota->charged_from +
  2004. msecs_to_jiffies(quota->reset_interval))) {
  2005. if (quota->esz && quota->charged_sz >= quota->esz)
  2006. s->stat.qt_exceeds++;
  2007. quota->total_charged_sz += quota->charged_sz;
  2008. quota->charged_from = jiffies;
  2009. quota->charged_sz = 0;
  2010. if (trace_damos_esz_enabled())
  2011. cached_esz = quota->esz;
  2012. damos_set_effective_quota(quota);
  2013. if (trace_damos_esz_enabled() && quota->esz != cached_esz)
  2014. damos_trace_esz(c, s, quota);
  2015. }
  2016. if (!c->ops.get_scheme_score)
  2017. return;
  2018. /* Fill up the score histogram */
  2019. memset(c->regions_score_histogram, 0,
  2020. sizeof(*c->regions_score_histogram) *
  2021. (DAMOS_MAX_SCORE + 1));
  2022. damon_for_each_target(t, c) {
  2023. damon_for_each_region(r, t) {
  2024. if (!__damos_valid_target(r, s))
  2025. continue;
  2026. score = c->ops.get_scheme_score(c, t, r, s);
  2027. c->regions_score_histogram[score] +=
  2028. damon_sz_region(r);
  2029. if (score > max_score)
  2030. max_score = score;
  2031. }
  2032. }
  2033. /* Set the min score limit */
  2034. for (cumulated_sz = 0, score = max_score; ; score--) {
  2035. cumulated_sz += c->regions_score_histogram[score];
  2036. if (cumulated_sz >= quota->esz || !score)
  2037. break;
  2038. }
  2039. quota->min_score = score;
  2040. }
  2041. static void damos_trace_stat(struct damon_ctx *c, struct damos *s)
  2042. {
  2043. unsigned int cidx = 0, sidx = 0;
  2044. struct damos *siter;
  2045. if (!trace_damos_stat_after_apply_interval_enabled())
  2046. return;
  2047. damon_for_each_scheme(siter, c) {
  2048. if (siter == s)
  2049. break;
  2050. sidx++;
  2051. }
  2052. trace_damos_stat_after_apply_interval(cidx, sidx, &s->stat);
  2053. }
  2054. static void kdamond_apply_schemes(struct damon_ctx *c)
  2055. {
  2056. struct damon_target *t;
  2057. struct damon_region *r, *next_r;
  2058. struct damos *s;
  2059. unsigned long sample_interval = c->attrs.sample_interval ?
  2060. c->attrs.sample_interval : 1;
  2061. bool has_schemes_to_apply = false;
  2062. damon_for_each_scheme(s, c) {
  2063. if (c->passed_sample_intervals < s->next_apply_sis)
  2064. continue;
  2065. if (!s->wmarks.activated)
  2066. continue;
  2067. has_schemes_to_apply = true;
  2068. damos_adjust_quota(c, s);
  2069. }
  2070. if (!has_schemes_to_apply)
  2071. return;
  2072. mutex_lock(&c->walk_control_lock);
  2073. damon_for_each_target(t, c) {
  2074. if (c->ops.target_valid && c->ops.target_valid(t) == false)
  2075. continue;
  2076. damon_for_each_region_safe(r, next_r, t)
  2077. damon_do_apply_schemes(c, t, r);
  2078. }
  2079. damon_for_each_scheme(s, c) {
  2080. if (c->passed_sample_intervals < s->next_apply_sis)
  2081. continue;
  2082. damos_walk_complete(c, s);
  2083. s->next_apply_sis = c->passed_sample_intervals +
  2084. (s->apply_interval_us ? s->apply_interval_us :
  2085. c->attrs.aggr_interval) / sample_interval;
  2086. s->last_applied = NULL;
  2087. damos_trace_stat(c, s);
  2088. }
  2089. mutex_unlock(&c->walk_control_lock);
  2090. }
  2091. /*
  2092. * Merge two adjacent regions into one region
  2093. */
  2094. static void damon_merge_two_regions(struct damon_target *t,
  2095. struct damon_region *l, struct damon_region *r)
  2096. {
  2097. unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
  2098. l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
  2099. (sz_l + sz_r);
  2100. l->nr_accesses_bp = l->nr_accesses * 10000;
  2101. l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
  2102. l->ar.end = r->ar.end;
  2103. damon_destroy_region(r, t);
  2104. }
  2105. /*
  2106. * Merge adjacent regions having similar access frequencies
  2107. *
  2108. * t target affected by this merge operation
  2109. * thres '->nr_accesses' diff threshold for the merge
  2110. * sz_limit size upper limit of each region
  2111. */
  2112. static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
  2113. unsigned long sz_limit)
  2114. {
  2115. struct damon_region *r, *prev = NULL, *next;
  2116. damon_for_each_region_safe(r, next, t) {
  2117. if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
  2118. r->age = 0;
  2119. else if ((r->nr_accesses == 0) != (r->last_nr_accesses == 0))
  2120. r->age = 0;
  2121. else
  2122. r->age++;
  2123. if (prev && prev->ar.end == r->ar.start &&
  2124. abs(prev->nr_accesses - r->nr_accesses) <= thres &&
  2125. damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
  2126. damon_merge_two_regions(t, prev, r);
  2127. else
  2128. prev = r;
  2129. }
  2130. }
  2131. /*
  2132. * Merge adjacent regions having similar access frequencies
  2133. *
  2134. * threshold '->nr_accesses' diff threshold for the merge
  2135. * sz_limit size upper limit of each region
  2136. *
  2137. * This function merges monitoring target regions which are adjacent and their
  2138. * access frequencies are similar. This is for minimizing the monitoring
  2139. * overhead under the dynamically changeable access pattern. If a merge was
  2140. * unnecessarily made, later 'kdamond_split_regions()' will revert it.
  2141. *
  2142. * The total number of regions could be higher than the user-defined limit,
  2143. * max_nr_regions for some cases. For example, the user can update
  2144. * max_nr_regions to a number that lower than the current number of regions
  2145. * while DAMON is running. For such a case, repeat merging until the limit is
  2146. * met while increasing @threshold up to possible maximum level.
  2147. */
  2148. static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
  2149. unsigned long sz_limit)
  2150. {
  2151. struct damon_target *t;
  2152. unsigned int nr_regions;
  2153. unsigned int max_thres;
  2154. max_thres = c->attrs.aggr_interval /
  2155. (c->attrs.sample_interval ? c->attrs.sample_interval : 1);
  2156. do {
  2157. nr_regions = 0;
  2158. damon_for_each_target(t, c) {
  2159. damon_merge_regions_of(t, threshold, sz_limit);
  2160. nr_regions += damon_nr_regions(t);
  2161. }
  2162. threshold = max(1, threshold * 2);
  2163. } while (nr_regions > c->attrs.max_nr_regions &&
  2164. threshold / 2 < max_thres);
  2165. }
  2166. /*
  2167. * Split a region in two
  2168. *
  2169. * r the region to be split
  2170. * sz_r size of the first sub-region that will be made
  2171. */
  2172. static void damon_split_region_at(struct damon_target *t,
  2173. struct damon_region *r, unsigned long sz_r)
  2174. {
  2175. struct damon_region *new;
  2176. new = damon_new_region(r->ar.start + sz_r, r->ar.end);
  2177. if (!new)
  2178. return;
  2179. r->ar.end = new->ar.start;
  2180. new->age = r->age;
  2181. new->last_nr_accesses = r->last_nr_accesses;
  2182. new->nr_accesses_bp = r->nr_accesses_bp;
  2183. new->nr_accesses = r->nr_accesses;
  2184. damon_insert_region(new, r, damon_next_region(r), t);
  2185. }
  2186. /* Split every region in the given target into 'nr_subs' regions */
  2187. static void damon_split_regions_of(struct damon_target *t, int nr_subs,
  2188. unsigned long min_region_sz)
  2189. {
  2190. struct damon_region *r, *next;
  2191. unsigned long sz_region, sz_sub = 0;
  2192. int i;
  2193. damon_for_each_region_safe(r, next, t) {
  2194. sz_region = damon_sz_region(r);
  2195. for (i = 0; i < nr_subs - 1 &&
  2196. sz_region > 2 * min_region_sz; i++) {
  2197. /*
  2198. * Randomly select size of left sub-region to be at
  2199. * least 10 percent and at most 90% of original region
  2200. */
  2201. sz_sub = ALIGN_DOWN(damon_rand(1, 10) *
  2202. sz_region / 10, min_region_sz);
  2203. /* Do not allow blank region */
  2204. if (sz_sub == 0 || sz_sub >= sz_region)
  2205. continue;
  2206. damon_split_region_at(t, r, sz_sub);
  2207. sz_region = sz_sub;
  2208. }
  2209. }
  2210. }
  2211. /*
  2212. * Split every target region into randomly-sized small regions
  2213. *
  2214. * This function splits every target region into random-sized small regions if
  2215. * current total number of the regions is equal or smaller than half of the
  2216. * user-specified maximum number of regions. This is for maximizing the
  2217. * monitoring accuracy under the dynamically changeable access patterns. If a
  2218. * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
  2219. * it.
  2220. */
  2221. static void kdamond_split_regions(struct damon_ctx *ctx)
  2222. {
  2223. struct damon_target *t;
  2224. unsigned int nr_regions = 0;
  2225. static unsigned int last_nr_regions;
  2226. int nr_subregions = 2;
  2227. damon_for_each_target(t, ctx)
  2228. nr_regions += damon_nr_regions(t);
  2229. if (nr_regions > ctx->attrs.max_nr_regions / 2)
  2230. return;
  2231. /* Maybe the middle of the region has different access frequency */
  2232. if (last_nr_regions == nr_regions &&
  2233. nr_regions < ctx->attrs.max_nr_regions / 3)
  2234. nr_subregions = 3;
  2235. damon_for_each_target(t, ctx)
  2236. damon_split_regions_of(t, nr_subregions, ctx->min_region_sz);
  2237. last_nr_regions = nr_regions;
  2238. }
  2239. /*
  2240. * Check whether current monitoring should be stopped
  2241. *
  2242. * The monitoring is stopped when either the user requested to stop, or all
  2243. * monitoring targets are invalid.
  2244. *
  2245. * Returns true if need to stop current monitoring.
  2246. */
  2247. static bool kdamond_need_stop(struct damon_ctx *ctx)
  2248. {
  2249. struct damon_target *t;
  2250. if (kthread_should_stop())
  2251. return true;
  2252. if (!ctx->ops.target_valid)
  2253. return false;
  2254. damon_for_each_target(t, ctx) {
  2255. if (ctx->ops.target_valid(t))
  2256. return false;
  2257. }
  2258. return true;
  2259. }
  2260. static int damos_get_wmark_metric_value(enum damos_wmark_metric metric,
  2261. unsigned long *metric_value)
  2262. {
  2263. switch (metric) {
  2264. case DAMOS_WMARK_FREE_MEM_RATE:
  2265. *metric_value = global_zone_page_state(NR_FREE_PAGES) * 1000 /
  2266. totalram_pages();
  2267. return 0;
  2268. default:
  2269. break;
  2270. }
  2271. return -EINVAL;
  2272. }
  2273. /*
  2274. * Returns zero if the scheme is active. Else, returns time to wait for next
  2275. * watermark check in micro-seconds.
  2276. */
  2277. static unsigned long damos_wmark_wait_us(struct damos *scheme)
  2278. {
  2279. unsigned long metric;
  2280. if (damos_get_wmark_metric_value(scheme->wmarks.metric, &metric))
  2281. return 0;
  2282. /* higher than high watermark or lower than low watermark */
  2283. if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
  2284. if (scheme->wmarks.activated)
  2285. pr_debug("deactivate a scheme (%d) for %s wmark\n",
  2286. scheme->action,
  2287. str_high_low(metric > scheme->wmarks.high));
  2288. scheme->wmarks.activated = false;
  2289. return scheme->wmarks.interval;
  2290. }
  2291. /* inactive and higher than middle watermark */
  2292. if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
  2293. !scheme->wmarks.activated)
  2294. return scheme->wmarks.interval;
  2295. if (!scheme->wmarks.activated)
  2296. pr_debug("activate a scheme (%d)\n", scheme->action);
  2297. scheme->wmarks.activated = true;
  2298. return 0;
  2299. }
  2300. static void kdamond_usleep(unsigned long usecs)
  2301. {
  2302. if (usecs >= USLEEP_RANGE_UPPER_BOUND)
  2303. schedule_timeout_idle(usecs_to_jiffies(usecs));
  2304. else
  2305. usleep_range_idle(usecs, usecs + 1);
  2306. }
  2307. /*
  2308. * kdamond_call() - handle damon_call_control objects.
  2309. * @ctx: The &struct damon_ctx of the kdamond.
  2310. * @cancel: Whether to cancel the invocation of the function.
  2311. *
  2312. * If there are &struct damon_call_control requests that registered via
  2313. * &damon_call() on @ctx, do or cancel the invocation of the function depending
  2314. * on @cancel. @cancel is set when the kdamond is already out of the main loop
  2315. * and therefore will be terminated.
  2316. */
  2317. static void kdamond_call(struct damon_ctx *ctx, bool cancel)
  2318. {
  2319. struct damon_call_control *control, *next;
  2320. LIST_HEAD(controls);
  2321. mutex_lock(&ctx->call_controls_lock);
  2322. list_splice_tail_init(&ctx->call_controls, &controls);
  2323. mutex_unlock(&ctx->call_controls_lock);
  2324. list_for_each_entry_safe(control, next, &controls, list) {
  2325. if (!control->repeat || cancel)
  2326. list_del(&control->list);
  2327. if (cancel)
  2328. control->canceled = true;
  2329. else
  2330. control->return_code = control->fn(control->data);
  2331. if (!control->repeat)
  2332. complete(&control->completion);
  2333. else if (control->canceled && control->dealloc_on_cancel)
  2334. kfree(control);
  2335. if (!cancel && ctx->maybe_corrupted)
  2336. break;
  2337. }
  2338. mutex_lock(&ctx->call_controls_lock);
  2339. list_splice_tail(&controls, &ctx->call_controls);
  2340. mutex_unlock(&ctx->call_controls_lock);
  2341. }
  2342. /* Returns negative error code if it's not activated but should return */
  2343. static int kdamond_wait_activation(struct damon_ctx *ctx)
  2344. {
  2345. struct damos *s;
  2346. unsigned long wait_time;
  2347. unsigned long min_wait_time = 0;
  2348. bool init_wait_time = false;
  2349. while (!kdamond_need_stop(ctx)) {
  2350. damon_for_each_scheme(s, ctx) {
  2351. wait_time = damos_wmark_wait_us(s);
  2352. if (!init_wait_time || wait_time < min_wait_time) {
  2353. init_wait_time = true;
  2354. min_wait_time = wait_time;
  2355. }
  2356. }
  2357. if (!min_wait_time)
  2358. return 0;
  2359. kdamond_usleep(min_wait_time);
  2360. kdamond_call(ctx, false);
  2361. if (ctx->maybe_corrupted)
  2362. return -EINVAL;
  2363. damos_walk_cancel(ctx);
  2364. }
  2365. return -EBUSY;
  2366. }
  2367. static void kdamond_init_ctx(struct damon_ctx *ctx)
  2368. {
  2369. unsigned long sample_interval = ctx->attrs.sample_interval ?
  2370. ctx->attrs.sample_interval : 1;
  2371. unsigned long apply_interval;
  2372. struct damos *scheme;
  2373. ctx->passed_sample_intervals = 0;
  2374. ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval;
  2375. ctx->next_ops_update_sis = ctx->attrs.ops_update_interval /
  2376. sample_interval;
  2377. ctx->next_intervals_tune_sis = ctx->next_aggregation_sis *
  2378. ctx->attrs.intervals_goal.aggrs;
  2379. damon_for_each_scheme(scheme, ctx) {
  2380. apply_interval = scheme->apply_interval_us ?
  2381. scheme->apply_interval_us : ctx->attrs.aggr_interval;
  2382. scheme->next_apply_sis = apply_interval / sample_interval;
  2383. damos_set_filters_default_reject(scheme);
  2384. }
  2385. }
  2386. /*
  2387. * The monitoring daemon that runs as a kernel thread
  2388. */
  2389. static int kdamond_fn(void *data)
  2390. {
  2391. struct damon_ctx *ctx = data;
  2392. unsigned int max_nr_accesses = 0;
  2393. unsigned long sz_limit = 0;
  2394. pr_debug("kdamond (%d) starts\n", current->pid);
  2395. complete(&ctx->kdamond_started);
  2396. kdamond_init_ctx(ctx);
  2397. if (ctx->ops.init)
  2398. ctx->ops.init(ctx);
  2399. ctx->regions_score_histogram = kmalloc_array(DAMOS_MAX_SCORE + 1,
  2400. sizeof(*ctx->regions_score_histogram), GFP_KERNEL);
  2401. if (!ctx->regions_score_histogram)
  2402. goto done;
  2403. sz_limit = damon_region_sz_limit(ctx);
  2404. while (!kdamond_need_stop(ctx)) {
  2405. /*
  2406. * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could
  2407. * be changed from kdamond_call(). Read the values here, and
  2408. * use those for this iteration. That is, damon_set_attrs()
  2409. * updated new values are respected from next iteration.
  2410. */
  2411. unsigned long next_aggregation_sis = ctx->next_aggregation_sis;
  2412. unsigned long next_ops_update_sis = ctx->next_ops_update_sis;
  2413. unsigned long sample_interval = ctx->attrs.sample_interval;
  2414. if (kdamond_wait_activation(ctx))
  2415. break;
  2416. if (ctx->ops.prepare_access_checks)
  2417. ctx->ops.prepare_access_checks(ctx);
  2418. kdamond_usleep(sample_interval);
  2419. ctx->passed_sample_intervals++;
  2420. if (ctx->ops.check_accesses)
  2421. max_nr_accesses = ctx->ops.check_accesses(ctx);
  2422. if (ctx->passed_sample_intervals >= next_aggregation_sis)
  2423. kdamond_merge_regions(ctx,
  2424. max_nr_accesses / 10,
  2425. sz_limit);
  2426. /*
  2427. * do kdamond_call() and kdamond_apply_schemes() after
  2428. * kdamond_merge_regions() if possible, to reduce overhead
  2429. */
  2430. kdamond_call(ctx, false);
  2431. if (ctx->maybe_corrupted)
  2432. break;
  2433. if (!list_empty(&ctx->schemes))
  2434. kdamond_apply_schemes(ctx);
  2435. else
  2436. damos_walk_cancel(ctx);
  2437. sample_interval = ctx->attrs.sample_interval ?
  2438. ctx->attrs.sample_interval : 1;
  2439. if (ctx->passed_sample_intervals >= next_aggregation_sis) {
  2440. if (ctx->attrs.intervals_goal.aggrs &&
  2441. ctx->passed_sample_intervals >=
  2442. ctx->next_intervals_tune_sis) {
  2443. /*
  2444. * ctx->next_aggregation_sis might be updated
  2445. * from kdamond_call(). In the case,
  2446. * damon_set_attrs() which will be called from
  2447. * kdamond_tune_interval() may wrongly think
  2448. * this is in the middle of the current
  2449. * aggregation, and make aggregation
  2450. * information reset for all regions. Then,
  2451. * following kdamond_reset_aggregated() call
  2452. * will make the region information invalid,
  2453. * particularly for ->nr_accesses_bp.
  2454. *
  2455. * Reset ->next_aggregation_sis to avoid that.
  2456. * It will anyway correctly updated after this
  2457. * if clause.
  2458. */
  2459. ctx->next_aggregation_sis =
  2460. next_aggregation_sis;
  2461. ctx->next_intervals_tune_sis +=
  2462. ctx->attrs.aggr_samples *
  2463. ctx->attrs.intervals_goal.aggrs;
  2464. kdamond_tune_intervals(ctx);
  2465. sample_interval = ctx->attrs.sample_interval ?
  2466. ctx->attrs.sample_interval : 1;
  2467. }
  2468. ctx->next_aggregation_sis = next_aggregation_sis +
  2469. ctx->attrs.aggr_interval / sample_interval;
  2470. kdamond_reset_aggregated(ctx);
  2471. kdamond_split_regions(ctx);
  2472. }
  2473. if (ctx->passed_sample_intervals >= next_ops_update_sis) {
  2474. ctx->next_ops_update_sis = next_ops_update_sis +
  2475. ctx->attrs.ops_update_interval /
  2476. sample_interval;
  2477. if (ctx->ops.update)
  2478. ctx->ops.update(ctx);
  2479. sz_limit = damon_region_sz_limit(ctx);
  2480. }
  2481. }
  2482. done:
  2483. damon_destroy_targets(ctx);
  2484. kfree(ctx->regions_score_histogram);
  2485. kdamond_call(ctx, true);
  2486. damos_walk_cancel(ctx);
  2487. pr_debug("kdamond (%d) finishes\n", current->pid);
  2488. mutex_lock(&ctx->kdamond_lock);
  2489. ctx->kdamond = NULL;
  2490. mutex_unlock(&ctx->kdamond_lock);
  2491. mutex_lock(&damon_lock);
  2492. nr_running_ctxs--;
  2493. if (!nr_running_ctxs && running_exclusive_ctxs)
  2494. running_exclusive_ctxs = false;
  2495. mutex_unlock(&damon_lock);
  2496. return 0;
  2497. }
  2498. static int walk_system_ram(struct resource *res, void *arg)
  2499. {
  2500. struct damon_addr_range *a = arg;
  2501. if (a->end - a->start < resource_size(res)) {
  2502. a->start = res->start;
  2503. a->end = res->end;
  2504. }
  2505. return 0;
  2506. }
  2507. /*
  2508. * Find biggest 'System RAM' resource and store its start and end address in
  2509. * @start and @end, respectively. If no System RAM is found, returns false.
  2510. */
  2511. static bool damon_find_biggest_system_ram(unsigned long *start,
  2512. unsigned long *end)
  2513. {
  2514. struct damon_addr_range arg = {};
  2515. walk_system_ram_res(0, ULONG_MAX, &arg, walk_system_ram);
  2516. if (arg.end <= arg.start)
  2517. return false;
  2518. *start = arg.start;
  2519. *end = arg.end;
  2520. return true;
  2521. }
  2522. /**
  2523. * damon_set_region_biggest_system_ram_default() - Set the region of the given
  2524. * monitoring target as requested, or biggest 'System RAM'.
  2525. * @t: The monitoring target to set the region.
  2526. * @start: The pointer to the start address of the region.
  2527. * @end: The pointer to the end address of the region.
  2528. * @min_region_sz: Minimum region size.
  2529. *
  2530. * This function sets the region of @t as requested by @start and @end. If the
  2531. * values of @start and @end are zero, however, this function finds the biggest
  2532. * 'System RAM' resource and sets the region to cover the resource. In the
  2533. * latter case, this function saves the start and end addresses of the resource
  2534. * in @start and @end, respectively.
  2535. *
  2536. * Return: 0 on success, negative error code otherwise.
  2537. */
  2538. int damon_set_region_biggest_system_ram_default(struct damon_target *t,
  2539. unsigned long *start, unsigned long *end,
  2540. unsigned long min_region_sz)
  2541. {
  2542. struct damon_addr_range addr_range;
  2543. if (*start > *end)
  2544. return -EINVAL;
  2545. if (!*start && !*end &&
  2546. !damon_find_biggest_system_ram(start, end))
  2547. return -EINVAL;
  2548. addr_range.start = *start;
  2549. addr_range.end = *end;
  2550. return damon_set_regions(t, &addr_range, 1, min_region_sz);
  2551. }
  2552. /*
  2553. * damon_moving_sum() - Calculate an inferred moving sum value.
  2554. * @mvsum: Inferred sum of the last @len_window values.
  2555. * @nomvsum: Non-moving sum of the last discrete @len_window window values.
  2556. * @len_window: The number of last values to take care of.
  2557. * @new_value: New value that will be added to the pseudo moving sum.
  2558. *
  2559. * Moving sum (moving average * window size) is good for handling noise, but
  2560. * the cost of keeping past values can be high for arbitrary window size. This
  2561. * function implements a lightweight pseudo moving sum function that doesn't
  2562. * keep the past window values.
  2563. *
  2564. * It simply assumes there was no noise in the past, and get the no-noise
  2565. * assumed past value to drop from @nomvsum and @len_window. @nomvsum is a
  2566. * non-moving sum of the last window. For example, if @len_window is 10 and we
  2567. * have 25 values, @nomvsum is the sum of the 11th to 20th values of the 25
  2568. * values. Hence, this function simply drops @nomvsum / @len_window from
  2569. * given @mvsum and add @new_value.
  2570. *
  2571. * For example, if @len_window is 10 and @nomvsum is 50, the last 10 values for
  2572. * the last window could be vary, e.g., 0, 10, 0, 10, 0, 10, 0, 0, 0, 20. For
  2573. * calculating next moving sum with a new value, we should drop 0 from 50 and
  2574. * add the new value. However, this function assumes it got value 5 for each
  2575. * of the last ten times. Based on the assumption, when the next value is
  2576. * measured, it drops the assumed past value, 5 from the current sum, and add
  2577. * the new value to get the updated pseduo-moving average.
  2578. *
  2579. * This means the value could have errors, but the errors will be disappeared
  2580. * for every @len_window aligned calls. For example, if @len_window is 10, the
  2581. * pseudo moving sum with 11th value to 19th value would have an error. But
  2582. * the sum with 20th value will not have the error.
  2583. *
  2584. * Return: Pseudo-moving average after getting the @new_value.
  2585. */
  2586. static unsigned int damon_moving_sum(unsigned int mvsum, unsigned int nomvsum,
  2587. unsigned int len_window, unsigned int new_value)
  2588. {
  2589. return mvsum - nomvsum / len_window + new_value;
  2590. }
  2591. /**
  2592. * damon_update_region_access_rate() - Update the access rate of a region.
  2593. * @r: The DAMON region to update for its access check result.
  2594. * @accessed: Whether the region has accessed during last sampling interval.
  2595. * @attrs: The damon_attrs of the DAMON context.
  2596. *
  2597. * Update the access rate of a region with the region's last sampling interval
  2598. * access check result.
  2599. *
  2600. * Usually this will be called by &damon_operations->check_accesses callback.
  2601. */
  2602. void damon_update_region_access_rate(struct damon_region *r, bool accessed,
  2603. struct damon_attrs *attrs)
  2604. {
  2605. unsigned int len_window = 1;
  2606. /*
  2607. * sample_interval can be zero, but cannot be larger than
  2608. * aggr_interval, owing to validation of damon_set_attrs().
  2609. */
  2610. if (attrs->sample_interval)
  2611. len_window = damon_max_nr_accesses(attrs);
  2612. r->nr_accesses_bp = damon_moving_sum(r->nr_accesses_bp,
  2613. r->last_nr_accesses * 10000, len_window,
  2614. accessed ? 10000 : 0);
  2615. if (accessed)
  2616. r->nr_accesses++;
  2617. }
  2618. /**
  2619. * damon_initialized() - Return if DAMON is ready to be used.
  2620. *
  2621. * Return: true if DAMON is ready to be used, false otherwise.
  2622. */
  2623. bool damon_initialized(void)
  2624. {
  2625. return damon_region_cache != NULL;
  2626. }
  2627. static int __init damon_init(void)
  2628. {
  2629. damon_region_cache = KMEM_CACHE(damon_region, 0);
  2630. if (unlikely(!damon_region_cache)) {
  2631. pr_err("creating damon_region_cache fails\n");
  2632. return -ENOMEM;
  2633. }
  2634. return 0;
  2635. }
  2636. subsys_initcall(damon_init);
  2637. #include "tests/core-kunit.h"