core.c 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244
  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/mm.h>
  12. #include <linux/psi.h>
  13. #include <linux/slab.h>
  14. #include <linux/string.h>
  15. #define CREATE_TRACE_POINTS
  16. #include <trace/events/damon.h>
  17. #ifdef CONFIG_DAMON_KUNIT_TEST
  18. #undef DAMON_MIN_REGION
  19. #define DAMON_MIN_REGION 1
  20. #endif
  21. static DEFINE_MUTEX(damon_lock);
  22. static int nr_running_ctxs;
  23. static bool running_exclusive_ctxs;
  24. static DEFINE_MUTEX(damon_ops_lock);
  25. static struct damon_operations damon_registered_ops[NR_DAMON_OPS];
  26. static struct kmem_cache *damon_region_cache __ro_after_init;
  27. /* Should be called under damon_ops_lock with id smaller than NR_DAMON_OPS */
  28. static bool __damon_is_registered_ops(enum damon_ops_id id)
  29. {
  30. struct damon_operations empty_ops = {};
  31. if (!memcmp(&empty_ops, &damon_registered_ops[id], sizeof(empty_ops)))
  32. return false;
  33. return true;
  34. }
  35. /**
  36. * damon_is_registered_ops() - Check if a given damon_operations is registered.
  37. * @id: Id of the damon_operations to check if registered.
  38. *
  39. * Return: true if the ops is set, false otherwise.
  40. */
  41. bool damon_is_registered_ops(enum damon_ops_id id)
  42. {
  43. bool registered;
  44. if (id >= NR_DAMON_OPS)
  45. return false;
  46. mutex_lock(&damon_ops_lock);
  47. registered = __damon_is_registered_ops(id);
  48. mutex_unlock(&damon_ops_lock);
  49. return registered;
  50. }
  51. /**
  52. * damon_register_ops() - Register a monitoring operations set to DAMON.
  53. * @ops: monitoring operations set to register.
  54. *
  55. * This function registers a monitoring operations set of valid &struct
  56. * damon_operations->id so that others can find and use them later.
  57. *
  58. * Return: 0 on success, negative error code otherwise.
  59. */
  60. int damon_register_ops(struct damon_operations *ops)
  61. {
  62. int err = 0;
  63. if (ops->id >= NR_DAMON_OPS)
  64. return -EINVAL;
  65. mutex_lock(&damon_ops_lock);
  66. /* Fail for already registered ops */
  67. if (__damon_is_registered_ops(ops->id)) {
  68. err = -EINVAL;
  69. goto out;
  70. }
  71. damon_registered_ops[ops->id] = *ops;
  72. out:
  73. mutex_unlock(&damon_ops_lock);
  74. return err;
  75. }
  76. /**
  77. * damon_select_ops() - Select a monitoring operations to use with the context.
  78. * @ctx: monitoring context to use the operations.
  79. * @id: id of the registered monitoring operations to select.
  80. *
  81. * This function finds registered monitoring operations set of @id and make
  82. * @ctx to use it.
  83. *
  84. * Return: 0 on success, negative error code otherwise.
  85. */
  86. int damon_select_ops(struct damon_ctx *ctx, enum damon_ops_id id)
  87. {
  88. int err = 0;
  89. if (id >= NR_DAMON_OPS)
  90. return -EINVAL;
  91. mutex_lock(&damon_ops_lock);
  92. if (!__damon_is_registered_ops(id))
  93. err = -EINVAL;
  94. else
  95. ctx->ops = damon_registered_ops[id];
  96. mutex_unlock(&damon_ops_lock);
  97. return err;
  98. }
  99. /*
  100. * Construct a damon_region struct
  101. *
  102. * Returns the pointer to the new struct if success, or NULL otherwise
  103. */
  104. struct damon_region *damon_new_region(unsigned long start, unsigned long end)
  105. {
  106. struct damon_region *region;
  107. region = kmem_cache_alloc(damon_region_cache, GFP_KERNEL);
  108. if (!region)
  109. return NULL;
  110. region->ar.start = start;
  111. region->ar.end = end;
  112. region->nr_accesses = 0;
  113. region->nr_accesses_bp = 0;
  114. INIT_LIST_HEAD(&region->list);
  115. region->age = 0;
  116. region->last_nr_accesses = 0;
  117. return region;
  118. }
  119. void damon_add_region(struct damon_region *r, struct damon_target *t)
  120. {
  121. list_add_tail(&r->list, &t->regions_list);
  122. t->nr_regions++;
  123. }
  124. static void damon_del_region(struct damon_region *r, struct damon_target *t)
  125. {
  126. list_del(&r->list);
  127. t->nr_regions--;
  128. }
  129. static void damon_free_region(struct damon_region *r)
  130. {
  131. kmem_cache_free(damon_region_cache, r);
  132. }
  133. void damon_destroy_region(struct damon_region *r, struct damon_target *t)
  134. {
  135. damon_del_region(r, t);
  136. damon_free_region(r);
  137. }
  138. /*
  139. * Check whether a region is intersecting an address range
  140. *
  141. * Returns true if it is.
  142. */
  143. static bool damon_intersect(struct damon_region *r,
  144. struct damon_addr_range *re)
  145. {
  146. return !(r->ar.end <= re->start || re->end <= r->ar.start);
  147. }
  148. /*
  149. * Fill holes in regions with new regions.
  150. */
  151. static int damon_fill_regions_holes(struct damon_region *first,
  152. struct damon_region *last, struct damon_target *t)
  153. {
  154. struct damon_region *r = first;
  155. damon_for_each_region_from(r, t) {
  156. struct damon_region *next, *newr;
  157. if (r == last)
  158. break;
  159. next = damon_next_region(r);
  160. if (r->ar.end != next->ar.start) {
  161. newr = damon_new_region(r->ar.end, next->ar.start);
  162. if (!newr)
  163. return -ENOMEM;
  164. damon_insert_region(newr, r, next, t);
  165. }
  166. }
  167. return 0;
  168. }
  169. /*
  170. * damon_set_regions() - Set regions of a target for given address ranges.
  171. * @t: the given target.
  172. * @ranges: array of new monitoring target ranges.
  173. * @nr_ranges: length of @ranges.
  174. *
  175. * This function adds new regions to, or modify existing regions of a
  176. * monitoring target to fit in specific ranges.
  177. *
  178. * Return: 0 if success, or negative error code otherwise.
  179. */
  180. int damon_set_regions(struct damon_target *t, struct damon_addr_range *ranges,
  181. unsigned int nr_ranges)
  182. {
  183. struct damon_region *r, *next;
  184. unsigned int i;
  185. int err;
  186. /* Remove regions which are not in the new ranges */
  187. damon_for_each_region_safe(r, next, t) {
  188. for (i = 0; i < nr_ranges; i++) {
  189. if (damon_intersect(r, &ranges[i]))
  190. break;
  191. }
  192. if (i == nr_ranges)
  193. damon_destroy_region(r, t);
  194. }
  195. r = damon_first_region(t);
  196. /* Add new regions or resize existing regions to fit in the ranges */
  197. for (i = 0; i < nr_ranges; i++) {
  198. struct damon_region *first = NULL, *last, *newr;
  199. struct damon_addr_range *range;
  200. range = &ranges[i];
  201. /* Get the first/last regions intersecting with the range */
  202. damon_for_each_region_from(r, t) {
  203. if (damon_intersect(r, range)) {
  204. if (!first)
  205. first = r;
  206. last = r;
  207. }
  208. if (r->ar.start >= range->end)
  209. break;
  210. }
  211. if (!first) {
  212. /* no region intersects with this range */
  213. newr = damon_new_region(
  214. ALIGN_DOWN(range->start,
  215. DAMON_MIN_REGION),
  216. ALIGN(range->end, DAMON_MIN_REGION));
  217. if (!newr)
  218. return -ENOMEM;
  219. damon_insert_region(newr, damon_prev_region(r), r, t);
  220. } else {
  221. /* resize intersecting regions to fit in this range */
  222. first->ar.start = ALIGN_DOWN(range->start,
  223. DAMON_MIN_REGION);
  224. last->ar.end = ALIGN(range->end, DAMON_MIN_REGION);
  225. /* fill possible holes in the range */
  226. err = damon_fill_regions_holes(first, last, t);
  227. if (err)
  228. return err;
  229. }
  230. }
  231. return 0;
  232. }
  233. struct damos_filter *damos_new_filter(enum damos_filter_type type,
  234. bool matching)
  235. {
  236. struct damos_filter *filter;
  237. filter = kmalloc(sizeof(*filter), GFP_KERNEL);
  238. if (!filter)
  239. return NULL;
  240. filter->type = type;
  241. filter->matching = matching;
  242. INIT_LIST_HEAD(&filter->list);
  243. return filter;
  244. }
  245. void damos_add_filter(struct damos *s, struct damos_filter *f)
  246. {
  247. list_add_tail(&f->list, &s->filters);
  248. }
  249. static void damos_del_filter(struct damos_filter *f)
  250. {
  251. list_del(&f->list);
  252. }
  253. static void damos_free_filter(struct damos_filter *f)
  254. {
  255. kfree(f);
  256. }
  257. void damos_destroy_filter(struct damos_filter *f)
  258. {
  259. damos_del_filter(f);
  260. damos_free_filter(f);
  261. }
  262. struct damos_quota_goal *damos_new_quota_goal(
  263. enum damos_quota_goal_metric metric,
  264. unsigned long target_value)
  265. {
  266. struct damos_quota_goal *goal;
  267. goal = kmalloc(sizeof(*goal), GFP_KERNEL);
  268. if (!goal)
  269. return NULL;
  270. goal->metric = metric;
  271. goal->target_value = target_value;
  272. INIT_LIST_HEAD(&goal->list);
  273. return goal;
  274. }
  275. void damos_add_quota_goal(struct damos_quota *q, struct damos_quota_goal *g)
  276. {
  277. list_add_tail(&g->list, &q->goals);
  278. }
  279. static void damos_del_quota_goal(struct damos_quota_goal *g)
  280. {
  281. list_del(&g->list);
  282. }
  283. static void damos_free_quota_goal(struct damos_quota_goal *g)
  284. {
  285. kfree(g);
  286. }
  287. void damos_destroy_quota_goal(struct damos_quota_goal *g)
  288. {
  289. damos_del_quota_goal(g);
  290. damos_free_quota_goal(g);
  291. }
  292. /* initialize fields of @quota that normally API users wouldn't set */
  293. static struct damos_quota *damos_quota_init(struct damos_quota *quota)
  294. {
  295. quota->esz = 0;
  296. quota->total_charged_sz = 0;
  297. quota->total_charged_ns = 0;
  298. quota->charged_sz = 0;
  299. quota->charged_from = 0;
  300. quota->charge_target_from = NULL;
  301. quota->charge_addr_from = 0;
  302. quota->esz_bp = 0;
  303. return quota;
  304. }
  305. struct damos *damon_new_scheme(struct damos_access_pattern *pattern,
  306. enum damos_action action,
  307. unsigned long apply_interval_us,
  308. struct damos_quota *quota,
  309. struct damos_watermarks *wmarks,
  310. int target_nid)
  311. {
  312. struct damos *scheme;
  313. scheme = kmalloc(sizeof(*scheme), GFP_KERNEL);
  314. if (!scheme)
  315. return NULL;
  316. scheme->pattern = *pattern;
  317. scheme->action = action;
  318. scheme->apply_interval_us = apply_interval_us;
  319. /*
  320. * next_apply_sis will be set when kdamond starts. While kdamond is
  321. * running, it will also updated when it is added to the DAMON context,
  322. * or damon_attrs are updated.
  323. */
  324. scheme->next_apply_sis = 0;
  325. INIT_LIST_HEAD(&scheme->filters);
  326. scheme->stat = (struct damos_stat){};
  327. INIT_LIST_HEAD(&scheme->list);
  328. scheme->quota = *(damos_quota_init(quota));
  329. /* quota.goals should be separately set by caller */
  330. INIT_LIST_HEAD(&scheme->quota.goals);
  331. scheme->wmarks = *wmarks;
  332. scheme->wmarks.activated = true;
  333. scheme->target_nid = target_nid;
  334. return scheme;
  335. }
  336. static void damos_set_next_apply_sis(struct damos *s, struct damon_ctx *ctx)
  337. {
  338. unsigned long sample_interval = ctx->attrs.sample_interval ?
  339. ctx->attrs.sample_interval : 1;
  340. unsigned long apply_interval = s->apply_interval_us ?
  341. s->apply_interval_us : ctx->attrs.aggr_interval;
  342. s->next_apply_sis = ctx->passed_sample_intervals +
  343. apply_interval / sample_interval;
  344. }
  345. void damon_add_scheme(struct damon_ctx *ctx, struct damos *s)
  346. {
  347. list_add_tail(&s->list, &ctx->schemes);
  348. damos_set_next_apply_sis(s, ctx);
  349. }
  350. static void damon_del_scheme(struct damos *s)
  351. {
  352. list_del(&s->list);
  353. }
  354. static void damon_free_scheme(struct damos *s)
  355. {
  356. kfree(s);
  357. }
  358. void damon_destroy_scheme(struct damos *s)
  359. {
  360. struct damos_quota_goal *g, *g_next;
  361. struct damos_filter *f, *next;
  362. damos_for_each_quota_goal_safe(g, g_next, &s->quota)
  363. damos_destroy_quota_goal(g);
  364. damos_for_each_filter_safe(f, next, s)
  365. damos_destroy_filter(f);
  366. damon_del_scheme(s);
  367. damon_free_scheme(s);
  368. }
  369. /*
  370. * Construct a damon_target struct
  371. *
  372. * Returns the pointer to the new struct if success, or NULL otherwise
  373. */
  374. struct damon_target *damon_new_target(void)
  375. {
  376. struct damon_target *t;
  377. t = kmalloc(sizeof(*t), GFP_KERNEL);
  378. if (!t)
  379. return NULL;
  380. t->pid = NULL;
  381. t->nr_regions = 0;
  382. INIT_LIST_HEAD(&t->regions_list);
  383. INIT_LIST_HEAD(&t->list);
  384. return t;
  385. }
  386. void damon_add_target(struct damon_ctx *ctx, struct damon_target *t)
  387. {
  388. list_add_tail(&t->list, &ctx->adaptive_targets);
  389. }
  390. bool damon_targets_empty(struct damon_ctx *ctx)
  391. {
  392. return list_empty(&ctx->adaptive_targets);
  393. }
  394. static void damon_del_target(struct damon_target *t)
  395. {
  396. list_del(&t->list);
  397. }
  398. void damon_free_target(struct damon_target *t)
  399. {
  400. struct damon_region *r, *next;
  401. damon_for_each_region_safe(r, next, t)
  402. damon_free_region(r);
  403. kfree(t);
  404. }
  405. void damon_destroy_target(struct damon_target *t)
  406. {
  407. damon_del_target(t);
  408. damon_free_target(t);
  409. }
  410. unsigned int damon_nr_regions(struct damon_target *t)
  411. {
  412. return t->nr_regions;
  413. }
  414. struct damon_ctx *damon_new_ctx(void)
  415. {
  416. struct damon_ctx *ctx;
  417. ctx = kzalloc(sizeof(*ctx), GFP_KERNEL);
  418. if (!ctx)
  419. return NULL;
  420. init_completion(&ctx->kdamond_started);
  421. ctx->attrs.sample_interval = 5 * 1000;
  422. ctx->attrs.aggr_interval = 100 * 1000;
  423. ctx->attrs.ops_update_interval = 60 * 1000 * 1000;
  424. ctx->passed_sample_intervals = 0;
  425. /* These will be set from kdamond_init_intervals_sis() */
  426. ctx->next_aggregation_sis = 0;
  427. ctx->next_ops_update_sis = 0;
  428. mutex_init(&ctx->kdamond_lock);
  429. ctx->attrs.min_nr_regions = 10;
  430. ctx->attrs.max_nr_regions = 1000;
  431. INIT_LIST_HEAD(&ctx->adaptive_targets);
  432. INIT_LIST_HEAD(&ctx->schemes);
  433. return ctx;
  434. }
  435. static void damon_destroy_targets(struct damon_ctx *ctx)
  436. {
  437. struct damon_target *t, *next_t;
  438. if (ctx->ops.cleanup) {
  439. ctx->ops.cleanup(ctx);
  440. return;
  441. }
  442. damon_for_each_target_safe(t, next_t, ctx)
  443. damon_destroy_target(t);
  444. }
  445. void damon_destroy_ctx(struct damon_ctx *ctx)
  446. {
  447. struct damos *s, *next_s;
  448. damon_destroy_targets(ctx);
  449. damon_for_each_scheme_safe(s, next_s, ctx)
  450. damon_destroy_scheme(s);
  451. kfree(ctx);
  452. }
  453. static unsigned int damon_age_for_new_attrs(unsigned int age,
  454. struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
  455. {
  456. return age * old_attrs->aggr_interval / new_attrs->aggr_interval;
  457. }
  458. /* convert access ratio in bp (per 10,000) to nr_accesses */
  459. static unsigned int damon_accesses_bp_to_nr_accesses(
  460. unsigned int accesses_bp, struct damon_attrs *attrs)
  461. {
  462. return accesses_bp * damon_max_nr_accesses(attrs) / 10000;
  463. }
  464. /*
  465. * Convert nr_accesses to access ratio in bp (per 10,000).
  466. *
  467. * Callers should ensure attrs.aggr_interval is not zero, like
  468. * damon_update_monitoring_results() does . Otherwise, divide-by-zero would
  469. * happen.
  470. */
  471. static unsigned int damon_nr_accesses_to_accesses_bp(
  472. unsigned int nr_accesses, struct damon_attrs *attrs)
  473. {
  474. return nr_accesses * 10000 / damon_max_nr_accesses(attrs);
  475. }
  476. static unsigned int damon_nr_accesses_for_new_attrs(unsigned int nr_accesses,
  477. struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
  478. {
  479. return damon_accesses_bp_to_nr_accesses(
  480. damon_nr_accesses_to_accesses_bp(
  481. nr_accesses, old_attrs),
  482. new_attrs);
  483. }
  484. static void damon_update_monitoring_result(struct damon_region *r,
  485. struct damon_attrs *old_attrs, struct damon_attrs *new_attrs)
  486. {
  487. r->nr_accesses = damon_nr_accesses_for_new_attrs(r->nr_accesses,
  488. old_attrs, new_attrs);
  489. r->nr_accesses_bp = r->nr_accesses * 10000;
  490. r->age = damon_age_for_new_attrs(r->age, old_attrs, new_attrs);
  491. }
  492. /*
  493. * region->nr_accesses is the number of sampling intervals in the last
  494. * aggregation interval that access to the region has found, and region->age is
  495. * the number of aggregation intervals that its access pattern has maintained.
  496. * For the reason, the real meaning of the two fields depend on current
  497. * sampling interval and aggregation interval. This function updates
  498. * ->nr_accesses and ->age of given damon_ctx's regions for new damon_attrs.
  499. */
  500. static void damon_update_monitoring_results(struct damon_ctx *ctx,
  501. struct damon_attrs *new_attrs)
  502. {
  503. struct damon_attrs *old_attrs = &ctx->attrs;
  504. struct damon_target *t;
  505. struct damon_region *r;
  506. /* if any interval is zero, simply forgive conversion */
  507. if (!old_attrs->sample_interval || !old_attrs->aggr_interval ||
  508. !new_attrs->sample_interval ||
  509. !new_attrs->aggr_interval)
  510. return;
  511. damon_for_each_target(t, ctx)
  512. damon_for_each_region(r, t)
  513. damon_update_monitoring_result(
  514. r, old_attrs, new_attrs);
  515. }
  516. /**
  517. * damon_set_attrs() - Set attributes for the monitoring.
  518. * @ctx: monitoring context
  519. * @attrs: monitoring attributes
  520. *
  521. * This function should be called while the kdamond is not running, or an
  522. * access check results aggregation is not ongoing (e.g., from
  523. * &struct damon_callback->after_aggregation or
  524. * &struct damon_callback->after_wmarks_check callbacks).
  525. *
  526. * Every time interval is in micro-seconds.
  527. *
  528. * Return: 0 on success, negative error code otherwise.
  529. */
  530. int damon_set_attrs(struct damon_ctx *ctx, struct damon_attrs *attrs)
  531. {
  532. unsigned long sample_interval = attrs->sample_interval ?
  533. attrs->sample_interval : 1;
  534. struct damos *s;
  535. if (attrs->min_nr_regions < 3)
  536. return -EINVAL;
  537. if (attrs->min_nr_regions > attrs->max_nr_regions)
  538. return -EINVAL;
  539. if (attrs->sample_interval > attrs->aggr_interval)
  540. return -EINVAL;
  541. ctx->next_aggregation_sis = ctx->passed_sample_intervals +
  542. attrs->aggr_interval / sample_interval;
  543. ctx->next_ops_update_sis = ctx->passed_sample_intervals +
  544. attrs->ops_update_interval / sample_interval;
  545. damon_update_monitoring_results(ctx, attrs);
  546. ctx->attrs = *attrs;
  547. damon_for_each_scheme(s, ctx)
  548. damos_set_next_apply_sis(s, ctx);
  549. return 0;
  550. }
  551. /**
  552. * damon_set_schemes() - Set data access monitoring based operation schemes.
  553. * @ctx: monitoring context
  554. * @schemes: array of the schemes
  555. * @nr_schemes: number of entries in @schemes
  556. *
  557. * This function should not be called while the kdamond of the context is
  558. * running.
  559. */
  560. void damon_set_schemes(struct damon_ctx *ctx, struct damos **schemes,
  561. ssize_t nr_schemes)
  562. {
  563. struct damos *s, *next;
  564. ssize_t i;
  565. damon_for_each_scheme_safe(s, next, ctx)
  566. damon_destroy_scheme(s);
  567. for (i = 0; i < nr_schemes; i++)
  568. damon_add_scheme(ctx, schemes[i]);
  569. }
  570. static struct damos_quota_goal *damos_nth_quota_goal(
  571. int n, struct damos_quota *q)
  572. {
  573. struct damos_quota_goal *goal;
  574. int i = 0;
  575. damos_for_each_quota_goal(goal, q) {
  576. if (i++ == n)
  577. return goal;
  578. }
  579. return NULL;
  580. }
  581. static void damos_commit_quota_goal(
  582. struct damos_quota_goal *dst, struct damos_quota_goal *src)
  583. {
  584. dst->metric = src->metric;
  585. dst->target_value = src->target_value;
  586. if (dst->metric == DAMOS_QUOTA_USER_INPUT)
  587. dst->current_value = src->current_value;
  588. /* keep last_psi_total as is, since it will be updated in next cycle */
  589. }
  590. /**
  591. * damos_commit_quota_goals() - Commit DAMOS quota goals to another quota.
  592. * @dst: The commit destination DAMOS quota.
  593. * @src: The commit source DAMOS quota.
  594. *
  595. * Copies user-specified parameters for quota goals from @src to @dst. Users
  596. * should use this function for quota goals-level parameters update of running
  597. * DAMON contexts, instead of manual in-place updates.
  598. *
  599. * This function should be called from parameters-update safe context, like
  600. * DAMON callbacks.
  601. */
  602. int damos_commit_quota_goals(struct damos_quota *dst, struct damos_quota *src)
  603. {
  604. struct damos_quota_goal *dst_goal, *next, *src_goal, *new_goal;
  605. int i = 0, j = 0;
  606. damos_for_each_quota_goal_safe(dst_goal, next, dst) {
  607. src_goal = damos_nth_quota_goal(i++, src);
  608. if (src_goal)
  609. damos_commit_quota_goal(dst_goal, src_goal);
  610. else
  611. damos_destroy_quota_goal(dst_goal);
  612. }
  613. damos_for_each_quota_goal_safe(src_goal, next, src) {
  614. if (j++ < i)
  615. continue;
  616. new_goal = damos_new_quota_goal(
  617. src_goal->metric, src_goal->target_value);
  618. if (!new_goal)
  619. return -ENOMEM;
  620. damos_add_quota_goal(dst, new_goal);
  621. }
  622. return 0;
  623. }
  624. static int damos_commit_quota(struct damos_quota *dst, struct damos_quota *src)
  625. {
  626. int err;
  627. dst->reset_interval = src->reset_interval;
  628. dst->ms = src->ms;
  629. dst->sz = src->sz;
  630. err = damos_commit_quota_goals(dst, src);
  631. if (err)
  632. return err;
  633. dst->weight_sz = src->weight_sz;
  634. dst->weight_nr_accesses = src->weight_nr_accesses;
  635. dst->weight_age = src->weight_age;
  636. return 0;
  637. }
  638. static struct damos_filter *damos_nth_filter(int n, struct damos *s)
  639. {
  640. struct damos_filter *filter;
  641. int i = 0;
  642. damos_for_each_filter(filter, s) {
  643. if (i++ == n)
  644. return filter;
  645. }
  646. return NULL;
  647. }
  648. static void damos_commit_filter_arg(
  649. struct damos_filter *dst, struct damos_filter *src)
  650. {
  651. switch (dst->type) {
  652. case DAMOS_FILTER_TYPE_MEMCG:
  653. dst->memcg_id = src->memcg_id;
  654. break;
  655. case DAMOS_FILTER_TYPE_ADDR:
  656. dst->addr_range = src->addr_range;
  657. break;
  658. case DAMOS_FILTER_TYPE_TARGET:
  659. dst->target_idx = src->target_idx;
  660. break;
  661. default:
  662. break;
  663. }
  664. }
  665. static void damos_commit_filter(
  666. struct damos_filter *dst, struct damos_filter *src)
  667. {
  668. dst->type = src->type;
  669. dst->matching = src->matching;
  670. damos_commit_filter_arg(dst, src);
  671. }
  672. static int damos_commit_filters(struct damos *dst, struct damos *src)
  673. {
  674. struct damos_filter *dst_filter, *next, *src_filter, *new_filter;
  675. int i = 0, j = 0;
  676. damos_for_each_filter_safe(dst_filter, next, dst) {
  677. src_filter = damos_nth_filter(i++, src);
  678. if (src_filter)
  679. damos_commit_filter(dst_filter, src_filter);
  680. else
  681. damos_destroy_filter(dst_filter);
  682. }
  683. damos_for_each_filter_safe(src_filter, next, src) {
  684. if (j++ < i)
  685. continue;
  686. new_filter = damos_new_filter(
  687. src_filter->type, src_filter->matching);
  688. if (!new_filter)
  689. return -ENOMEM;
  690. damos_commit_filter_arg(new_filter, src_filter);
  691. damos_add_filter(dst, new_filter);
  692. }
  693. return 0;
  694. }
  695. static struct damos *damon_nth_scheme(int n, struct damon_ctx *ctx)
  696. {
  697. struct damos *s;
  698. int i = 0;
  699. damon_for_each_scheme(s, ctx) {
  700. if (i++ == n)
  701. return s;
  702. }
  703. return NULL;
  704. }
  705. static int damos_commit(struct damos *dst, struct damos *src)
  706. {
  707. int err;
  708. dst->pattern = src->pattern;
  709. dst->action = src->action;
  710. dst->apply_interval_us = src->apply_interval_us;
  711. err = damos_commit_quota(&dst->quota, &src->quota);
  712. if (err)
  713. return err;
  714. dst->wmarks = src->wmarks;
  715. err = damos_commit_filters(dst, src);
  716. return err;
  717. }
  718. static int damon_commit_schemes(struct damon_ctx *dst, struct damon_ctx *src)
  719. {
  720. struct damos *dst_scheme, *next, *src_scheme, *new_scheme;
  721. int i = 0, j = 0, err;
  722. damon_for_each_scheme_safe(dst_scheme, next, dst) {
  723. src_scheme = damon_nth_scheme(i++, src);
  724. if (src_scheme) {
  725. err = damos_commit(dst_scheme, src_scheme);
  726. if (err)
  727. return err;
  728. } else {
  729. damon_destroy_scheme(dst_scheme);
  730. }
  731. }
  732. damon_for_each_scheme_safe(src_scheme, next, src) {
  733. if (j++ < i)
  734. continue;
  735. new_scheme = damon_new_scheme(&src_scheme->pattern,
  736. src_scheme->action,
  737. src_scheme->apply_interval_us,
  738. &src_scheme->quota, &src_scheme->wmarks,
  739. NUMA_NO_NODE);
  740. if (!new_scheme)
  741. return -ENOMEM;
  742. err = damos_commit(new_scheme, src_scheme);
  743. if (err) {
  744. damon_destroy_scheme(new_scheme);
  745. return err;
  746. }
  747. damon_add_scheme(dst, new_scheme);
  748. }
  749. return 0;
  750. }
  751. static struct damon_target *damon_nth_target(int n, struct damon_ctx *ctx)
  752. {
  753. struct damon_target *t;
  754. int i = 0;
  755. damon_for_each_target(t, ctx) {
  756. if (i++ == n)
  757. return t;
  758. }
  759. return NULL;
  760. }
  761. /*
  762. * The caller should ensure the regions of @src are
  763. * 1. valid (end >= src) and
  764. * 2. sorted by starting address.
  765. *
  766. * If @src has no region, @dst keeps current regions.
  767. */
  768. static int damon_commit_target_regions(
  769. struct damon_target *dst, struct damon_target *src)
  770. {
  771. struct damon_region *src_region;
  772. struct damon_addr_range *ranges;
  773. int i = 0, err;
  774. damon_for_each_region(src_region, src)
  775. i++;
  776. if (!i)
  777. return 0;
  778. ranges = kmalloc_array(i, sizeof(*ranges), GFP_KERNEL | __GFP_NOWARN);
  779. if (!ranges)
  780. return -ENOMEM;
  781. i = 0;
  782. damon_for_each_region(src_region, src)
  783. ranges[i++] = src_region->ar;
  784. err = damon_set_regions(dst, ranges, i);
  785. kfree(ranges);
  786. return err;
  787. }
  788. static int damon_commit_target(
  789. struct damon_target *dst, bool dst_has_pid,
  790. struct damon_target *src, bool src_has_pid)
  791. {
  792. int err;
  793. err = damon_commit_target_regions(dst, src);
  794. if (err)
  795. return err;
  796. if (dst_has_pid)
  797. put_pid(dst->pid);
  798. if (src_has_pid)
  799. get_pid(src->pid);
  800. dst->pid = src->pid;
  801. return 0;
  802. }
  803. static int damon_commit_targets(
  804. struct damon_ctx *dst, struct damon_ctx *src)
  805. {
  806. struct damon_target *dst_target, *next, *src_target, *new_target;
  807. int i = 0, j = 0, err;
  808. damon_for_each_target_safe(dst_target, next, dst) {
  809. src_target = damon_nth_target(i++, src);
  810. if (src_target) {
  811. err = damon_commit_target(
  812. dst_target, damon_target_has_pid(dst),
  813. src_target, damon_target_has_pid(src));
  814. if (err)
  815. return err;
  816. } else {
  817. if (damon_target_has_pid(dst))
  818. put_pid(dst_target->pid);
  819. damon_destroy_target(dst_target);
  820. }
  821. }
  822. damon_for_each_target_safe(src_target, next, src) {
  823. if (j++ < i)
  824. continue;
  825. new_target = damon_new_target();
  826. if (!new_target)
  827. return -ENOMEM;
  828. err = damon_commit_target(new_target, false,
  829. src_target, damon_target_has_pid(src));
  830. if (err) {
  831. damon_destroy_target(new_target);
  832. return err;
  833. }
  834. damon_add_target(dst, new_target);
  835. }
  836. return 0;
  837. }
  838. /**
  839. * damon_commit_ctx() - Commit parameters of a DAMON context to another.
  840. * @dst: The commit destination DAMON context.
  841. * @src: The commit source DAMON context.
  842. *
  843. * This function copies user-specified parameters from @src to @dst and update
  844. * the internal status and results accordingly. Users should use this function
  845. * for context-level parameters update of running context, instead of manual
  846. * in-place updates.
  847. *
  848. * This function should be called from parameters-update safe context, like
  849. * DAMON callbacks.
  850. */
  851. int damon_commit_ctx(struct damon_ctx *dst, struct damon_ctx *src)
  852. {
  853. int err;
  854. err = damon_commit_schemes(dst, src);
  855. if (err)
  856. return err;
  857. err = damon_commit_targets(dst, src);
  858. if (err)
  859. return err;
  860. /*
  861. * schemes and targets should be updated first, since
  862. * 1. damon_set_attrs() updates monitoring results of targets and
  863. * next_apply_sis of schemes, and
  864. * 2. ops update should be done after pid handling is done (target
  865. * committing require putting pids).
  866. */
  867. err = damon_set_attrs(dst, &src->attrs);
  868. if (err)
  869. return err;
  870. dst->ops = src->ops;
  871. return 0;
  872. }
  873. /**
  874. * damon_nr_running_ctxs() - Return number of currently running contexts.
  875. */
  876. int damon_nr_running_ctxs(void)
  877. {
  878. int nr_ctxs;
  879. mutex_lock(&damon_lock);
  880. nr_ctxs = nr_running_ctxs;
  881. mutex_unlock(&damon_lock);
  882. return nr_ctxs;
  883. }
  884. /* Returns the size upper limit for each monitoring region */
  885. static unsigned long damon_region_sz_limit(struct damon_ctx *ctx)
  886. {
  887. struct damon_target *t;
  888. struct damon_region *r;
  889. unsigned long sz = 0;
  890. damon_for_each_target(t, ctx) {
  891. damon_for_each_region(r, t)
  892. sz += damon_sz_region(r);
  893. }
  894. if (ctx->attrs.min_nr_regions)
  895. sz /= ctx->attrs.min_nr_regions;
  896. if (sz < DAMON_MIN_REGION)
  897. sz = DAMON_MIN_REGION;
  898. return sz;
  899. }
  900. static int kdamond_fn(void *data);
  901. /*
  902. * __damon_start() - Starts monitoring with given context.
  903. * @ctx: monitoring context
  904. *
  905. * This function should be called while damon_lock is hold.
  906. *
  907. * Return: 0 on success, negative error code otherwise.
  908. */
  909. static int __damon_start(struct damon_ctx *ctx)
  910. {
  911. int err = -EBUSY;
  912. mutex_lock(&ctx->kdamond_lock);
  913. if (!ctx->kdamond) {
  914. err = 0;
  915. reinit_completion(&ctx->kdamond_started);
  916. ctx->kdamond = kthread_run(kdamond_fn, ctx, "kdamond.%d",
  917. nr_running_ctxs);
  918. if (IS_ERR(ctx->kdamond)) {
  919. err = PTR_ERR(ctx->kdamond);
  920. ctx->kdamond = NULL;
  921. } else {
  922. wait_for_completion(&ctx->kdamond_started);
  923. }
  924. }
  925. mutex_unlock(&ctx->kdamond_lock);
  926. return err;
  927. }
  928. /**
  929. * damon_start() - Starts the monitorings for a given group of contexts.
  930. * @ctxs: an array of the pointers for contexts to start monitoring
  931. * @nr_ctxs: size of @ctxs
  932. * @exclusive: exclusiveness of this contexts group
  933. *
  934. * This function starts a group of monitoring threads for a group of monitoring
  935. * contexts. One thread per each context is created and run in parallel. The
  936. * caller should handle synchronization between the threads by itself. If
  937. * @exclusive is true and a group of threads that created by other
  938. * 'damon_start()' call is currently running, this function does nothing but
  939. * returns -EBUSY.
  940. *
  941. * Return: 0 on success, negative error code otherwise.
  942. */
  943. int damon_start(struct damon_ctx **ctxs, int nr_ctxs, bool exclusive)
  944. {
  945. int i;
  946. int err = 0;
  947. mutex_lock(&damon_lock);
  948. if ((exclusive && nr_running_ctxs) ||
  949. (!exclusive && running_exclusive_ctxs)) {
  950. mutex_unlock(&damon_lock);
  951. return -EBUSY;
  952. }
  953. for (i = 0; i < nr_ctxs; i++) {
  954. err = __damon_start(ctxs[i]);
  955. if (err)
  956. break;
  957. nr_running_ctxs++;
  958. }
  959. if (exclusive && nr_running_ctxs)
  960. running_exclusive_ctxs = true;
  961. mutex_unlock(&damon_lock);
  962. return err;
  963. }
  964. /*
  965. * __damon_stop() - Stops monitoring of a given context.
  966. * @ctx: monitoring context
  967. *
  968. * Return: 0 on success, negative error code otherwise.
  969. */
  970. static int __damon_stop(struct damon_ctx *ctx)
  971. {
  972. struct task_struct *tsk;
  973. mutex_lock(&ctx->kdamond_lock);
  974. tsk = ctx->kdamond;
  975. if (tsk) {
  976. get_task_struct(tsk);
  977. mutex_unlock(&ctx->kdamond_lock);
  978. kthread_stop_put(tsk);
  979. return 0;
  980. }
  981. mutex_unlock(&ctx->kdamond_lock);
  982. return -EPERM;
  983. }
  984. /**
  985. * damon_stop() - Stops the monitorings for a given group of contexts.
  986. * @ctxs: an array of the pointers for contexts to stop monitoring
  987. * @nr_ctxs: size of @ctxs
  988. *
  989. * Return: 0 on success, negative error code otherwise.
  990. */
  991. int damon_stop(struct damon_ctx **ctxs, int nr_ctxs)
  992. {
  993. int i, err = 0;
  994. for (i = 0; i < nr_ctxs; i++) {
  995. /* nr_running_ctxs is decremented in kdamond_fn */
  996. err = __damon_stop(ctxs[i]);
  997. if (err)
  998. break;
  999. }
  1000. return err;
  1001. }
  1002. /*
  1003. * Reset the aggregated monitoring results ('nr_accesses' of each region).
  1004. */
  1005. static void kdamond_reset_aggregated(struct damon_ctx *c)
  1006. {
  1007. struct damon_target *t;
  1008. unsigned int ti = 0; /* target's index */
  1009. damon_for_each_target(t, c) {
  1010. struct damon_region *r;
  1011. damon_for_each_region(r, t) {
  1012. trace_damon_aggregated(ti, r, damon_nr_regions(t));
  1013. r->last_nr_accesses = r->nr_accesses;
  1014. r->nr_accesses = 0;
  1015. }
  1016. ti++;
  1017. }
  1018. }
  1019. static void damon_split_region_at(struct damon_target *t,
  1020. struct damon_region *r, unsigned long sz_r);
  1021. static bool __damos_valid_target(struct damon_region *r, struct damos *s)
  1022. {
  1023. unsigned long sz;
  1024. unsigned int nr_accesses = r->nr_accesses_bp / 10000;
  1025. sz = damon_sz_region(r);
  1026. return s->pattern.min_sz_region <= sz &&
  1027. sz <= s->pattern.max_sz_region &&
  1028. s->pattern.min_nr_accesses <= nr_accesses &&
  1029. nr_accesses <= s->pattern.max_nr_accesses &&
  1030. s->pattern.min_age_region <= r->age &&
  1031. r->age <= s->pattern.max_age_region;
  1032. }
  1033. static bool damos_valid_target(struct damon_ctx *c, struct damon_target *t,
  1034. struct damon_region *r, struct damos *s)
  1035. {
  1036. bool ret = __damos_valid_target(r, s);
  1037. if (!ret || !s->quota.esz || !c->ops.get_scheme_score)
  1038. return ret;
  1039. return c->ops.get_scheme_score(c, t, r, s) >= s->quota.min_score;
  1040. }
  1041. /*
  1042. * damos_skip_charged_region() - Check if the given region or starting part of
  1043. * it is already charged for the DAMOS quota.
  1044. * @t: The target of the region.
  1045. * @rp: The pointer to the region.
  1046. * @s: The scheme to be applied.
  1047. *
  1048. * If a quota of a scheme has exceeded in a quota charge window, the scheme's
  1049. * action would applied to only a part of the target access pattern fulfilling
  1050. * regions. To avoid applying the scheme action to only already applied
  1051. * regions, DAMON skips applying the scheme action to the regions that charged
  1052. * in the previous charge window.
  1053. *
  1054. * This function checks if a given region should be skipped or not for the
  1055. * reason. If only the starting part of the region has previously charged,
  1056. * this function splits the region into two so that the second one covers the
  1057. * area that not charged in the previous charge widnow and saves the second
  1058. * region in *rp and returns false, so that the caller can apply DAMON action
  1059. * to the second one.
  1060. *
  1061. * Return: true if the region should be entirely skipped, false otherwise.
  1062. */
  1063. static bool damos_skip_charged_region(struct damon_target *t,
  1064. struct damon_region **rp, struct damos *s)
  1065. {
  1066. struct damon_region *r = *rp;
  1067. struct damos_quota *quota = &s->quota;
  1068. unsigned long sz_to_skip;
  1069. /* Skip previously charged regions */
  1070. if (quota->charge_target_from) {
  1071. if (t != quota->charge_target_from)
  1072. return true;
  1073. if (r == damon_last_region(t)) {
  1074. quota->charge_target_from = NULL;
  1075. quota->charge_addr_from = 0;
  1076. return true;
  1077. }
  1078. if (quota->charge_addr_from &&
  1079. r->ar.end <= quota->charge_addr_from)
  1080. return true;
  1081. if (quota->charge_addr_from && r->ar.start <
  1082. quota->charge_addr_from) {
  1083. sz_to_skip = ALIGN_DOWN(quota->charge_addr_from -
  1084. r->ar.start, DAMON_MIN_REGION);
  1085. if (!sz_to_skip) {
  1086. if (damon_sz_region(r) <= DAMON_MIN_REGION)
  1087. return true;
  1088. sz_to_skip = DAMON_MIN_REGION;
  1089. }
  1090. damon_split_region_at(t, r, sz_to_skip);
  1091. r = damon_next_region(r);
  1092. *rp = r;
  1093. }
  1094. quota->charge_target_from = NULL;
  1095. quota->charge_addr_from = 0;
  1096. }
  1097. return false;
  1098. }
  1099. static void damos_update_stat(struct damos *s,
  1100. unsigned long sz_tried, unsigned long sz_applied)
  1101. {
  1102. s->stat.nr_tried++;
  1103. s->stat.sz_tried += sz_tried;
  1104. if (sz_applied)
  1105. s->stat.nr_applied++;
  1106. s->stat.sz_applied += sz_applied;
  1107. }
  1108. static bool __damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
  1109. struct damon_region *r, struct damos_filter *filter)
  1110. {
  1111. bool matched = false;
  1112. struct damon_target *ti;
  1113. int target_idx = 0;
  1114. unsigned long start, end;
  1115. switch (filter->type) {
  1116. case DAMOS_FILTER_TYPE_TARGET:
  1117. damon_for_each_target(ti, ctx) {
  1118. if (ti == t)
  1119. break;
  1120. target_idx++;
  1121. }
  1122. matched = target_idx == filter->target_idx;
  1123. break;
  1124. case DAMOS_FILTER_TYPE_ADDR:
  1125. start = ALIGN_DOWN(filter->addr_range.start, DAMON_MIN_REGION);
  1126. end = ALIGN_DOWN(filter->addr_range.end, DAMON_MIN_REGION);
  1127. /* inside the range */
  1128. if (start <= r->ar.start && r->ar.end <= end) {
  1129. matched = true;
  1130. break;
  1131. }
  1132. /* outside of the range */
  1133. if (r->ar.end <= start || end <= r->ar.start) {
  1134. matched = false;
  1135. break;
  1136. }
  1137. /* start before the range and overlap */
  1138. if (r->ar.start < start) {
  1139. damon_split_region_at(t, r, start - r->ar.start);
  1140. matched = false;
  1141. break;
  1142. }
  1143. /* start inside the range */
  1144. damon_split_region_at(t, r, end - r->ar.start);
  1145. matched = true;
  1146. break;
  1147. default:
  1148. return false;
  1149. }
  1150. return matched == filter->matching;
  1151. }
  1152. static bool damos_filter_out(struct damon_ctx *ctx, struct damon_target *t,
  1153. struct damon_region *r, struct damos *s)
  1154. {
  1155. struct damos_filter *filter;
  1156. damos_for_each_filter(filter, s) {
  1157. if (__damos_filter_out(ctx, t, r, filter))
  1158. return true;
  1159. }
  1160. return false;
  1161. }
  1162. static void damos_apply_scheme(struct damon_ctx *c, struct damon_target *t,
  1163. struct damon_region *r, struct damos *s)
  1164. {
  1165. struct damos_quota *quota = &s->quota;
  1166. unsigned long sz = damon_sz_region(r);
  1167. struct timespec64 begin, end;
  1168. unsigned long sz_applied = 0;
  1169. int err = 0;
  1170. /*
  1171. * We plan to support multiple context per kdamond, as DAMON sysfs
  1172. * implies with 'nr_contexts' file. Nevertheless, only single context
  1173. * per kdamond is supported for now. So, we can simply use '0' context
  1174. * index here.
  1175. */
  1176. unsigned int cidx = 0;
  1177. struct damos *siter; /* schemes iterator */
  1178. unsigned int sidx = 0;
  1179. struct damon_target *titer; /* targets iterator */
  1180. unsigned int tidx = 0;
  1181. bool do_trace = false;
  1182. /* get indices for trace_damos_before_apply() */
  1183. if (trace_damos_before_apply_enabled()) {
  1184. damon_for_each_scheme(siter, c) {
  1185. if (siter == s)
  1186. break;
  1187. sidx++;
  1188. }
  1189. damon_for_each_target(titer, c) {
  1190. if (titer == t)
  1191. break;
  1192. tidx++;
  1193. }
  1194. do_trace = true;
  1195. }
  1196. if (c->ops.apply_scheme) {
  1197. if (quota->esz && quota->charged_sz + sz > quota->esz) {
  1198. sz = ALIGN_DOWN(quota->esz - quota->charged_sz,
  1199. DAMON_MIN_REGION);
  1200. if (!sz)
  1201. goto update_stat;
  1202. damon_split_region_at(t, r, sz);
  1203. }
  1204. if (damos_filter_out(c, t, r, s))
  1205. return;
  1206. ktime_get_coarse_ts64(&begin);
  1207. if (c->callback.before_damos_apply)
  1208. err = c->callback.before_damos_apply(c, t, r, s);
  1209. if (!err) {
  1210. trace_damos_before_apply(cidx, sidx, tidx, r,
  1211. damon_nr_regions(t), do_trace);
  1212. sz_applied = c->ops.apply_scheme(c, t, r, s);
  1213. }
  1214. ktime_get_coarse_ts64(&end);
  1215. quota->total_charged_ns += timespec64_to_ns(&end) -
  1216. timespec64_to_ns(&begin);
  1217. quota->charged_sz += sz;
  1218. if (quota->esz && quota->charged_sz >= quota->esz) {
  1219. quota->charge_target_from = t;
  1220. quota->charge_addr_from = r->ar.end + 1;
  1221. }
  1222. }
  1223. if (s->action != DAMOS_STAT)
  1224. r->age = 0;
  1225. update_stat:
  1226. damos_update_stat(s, sz, sz_applied);
  1227. }
  1228. static void damon_do_apply_schemes(struct damon_ctx *c,
  1229. struct damon_target *t,
  1230. struct damon_region *r)
  1231. {
  1232. struct damos *s;
  1233. damon_for_each_scheme(s, c) {
  1234. struct damos_quota *quota = &s->quota;
  1235. if (c->passed_sample_intervals < s->next_apply_sis)
  1236. continue;
  1237. if (!s->wmarks.activated)
  1238. continue;
  1239. /* Check the quota */
  1240. if (quota->esz && quota->charged_sz >= quota->esz)
  1241. continue;
  1242. if (damos_skip_charged_region(t, &r, s))
  1243. continue;
  1244. if (!damos_valid_target(c, t, r, s))
  1245. continue;
  1246. damos_apply_scheme(c, t, r, s);
  1247. }
  1248. }
  1249. /*
  1250. * damon_feed_loop_next_input() - get next input to achieve a target score.
  1251. * @last_input The last input.
  1252. * @score Current score that made with @last_input.
  1253. *
  1254. * Calculate next input to achieve the target score, based on the last input
  1255. * and current score. Assuming the input and the score are positively
  1256. * proportional, calculate how much compensation should be added to or
  1257. * subtracted from the last input as a proportion of the last input. Avoid
  1258. * next input always being zero by setting it non-zero always. In short form
  1259. * (assuming support of float and signed calculations), the algorithm is as
  1260. * below.
  1261. *
  1262. * next_input = max(last_input * ((goal - current) / goal + 1), 1)
  1263. *
  1264. * For simple implementation, we assume the target score is always 10,000. The
  1265. * caller should adjust @score for this.
  1266. *
  1267. * Returns next input that assumed to achieve the target score.
  1268. */
  1269. static unsigned long damon_feed_loop_next_input(unsigned long last_input,
  1270. unsigned long score)
  1271. {
  1272. const unsigned long goal = 10000;
  1273. /* Set minimum input as 10000 to avoid compensation be zero */
  1274. const unsigned long min_input = 10000;
  1275. unsigned long score_goal_diff, compensation;
  1276. bool over_achieving = score > goal;
  1277. if (score == goal)
  1278. return last_input;
  1279. if (score >= goal * 2)
  1280. return min_input;
  1281. if (over_achieving)
  1282. score_goal_diff = score - goal;
  1283. else
  1284. score_goal_diff = goal - score;
  1285. if (last_input < ULONG_MAX / score_goal_diff)
  1286. compensation = last_input * score_goal_diff / goal;
  1287. else
  1288. compensation = last_input / goal * score_goal_diff;
  1289. if (over_achieving)
  1290. return max(last_input - compensation, min_input);
  1291. if (last_input < ULONG_MAX - compensation)
  1292. return last_input + compensation;
  1293. return ULONG_MAX;
  1294. }
  1295. #ifdef CONFIG_PSI
  1296. static u64 damos_get_some_mem_psi_total(void)
  1297. {
  1298. if (static_branch_likely(&psi_disabled))
  1299. return 0;
  1300. return div_u64(psi_system.total[PSI_AVGS][PSI_MEM * 2],
  1301. NSEC_PER_USEC);
  1302. }
  1303. #else /* CONFIG_PSI */
  1304. static inline u64 damos_get_some_mem_psi_total(void)
  1305. {
  1306. return 0;
  1307. };
  1308. #endif /* CONFIG_PSI */
  1309. static void damos_set_quota_goal_current_value(struct damos_quota_goal *goal)
  1310. {
  1311. u64 now_psi_total;
  1312. switch (goal->metric) {
  1313. case DAMOS_QUOTA_USER_INPUT:
  1314. /* User should already set goal->current_value */
  1315. break;
  1316. case DAMOS_QUOTA_SOME_MEM_PSI_US:
  1317. now_psi_total = damos_get_some_mem_psi_total();
  1318. goal->current_value = now_psi_total - goal->last_psi_total;
  1319. goal->last_psi_total = now_psi_total;
  1320. break;
  1321. default:
  1322. break;
  1323. }
  1324. }
  1325. /* Return the highest score since it makes schemes least aggressive */
  1326. static unsigned long damos_quota_score(struct damos_quota *quota)
  1327. {
  1328. struct damos_quota_goal *goal;
  1329. unsigned long highest_score = 0;
  1330. damos_for_each_quota_goal(goal, quota) {
  1331. damos_set_quota_goal_current_value(goal);
  1332. highest_score = max(highest_score,
  1333. goal->current_value * 10000 /
  1334. goal->target_value);
  1335. }
  1336. return highest_score;
  1337. }
  1338. /*
  1339. * Called only if quota->ms, or quota->sz are set, or quota->goals is not empty
  1340. */
  1341. static void damos_set_effective_quota(struct damos_quota *quota)
  1342. {
  1343. unsigned long throughput;
  1344. unsigned long esz;
  1345. if (!quota->ms && list_empty(&quota->goals)) {
  1346. quota->esz = quota->sz;
  1347. return;
  1348. }
  1349. if (!list_empty(&quota->goals)) {
  1350. unsigned long score = damos_quota_score(quota);
  1351. quota->esz_bp = damon_feed_loop_next_input(
  1352. max(quota->esz_bp, 10000UL),
  1353. score);
  1354. esz = quota->esz_bp / 10000;
  1355. }
  1356. if (quota->ms) {
  1357. if (quota->total_charged_ns)
  1358. throughput = quota->total_charged_sz * 1000000 /
  1359. quota->total_charged_ns;
  1360. else
  1361. throughput = PAGE_SIZE * 1024;
  1362. if (!list_empty(&quota->goals))
  1363. esz = min(throughput * quota->ms, esz);
  1364. else
  1365. esz = throughput * quota->ms;
  1366. }
  1367. if (quota->sz && quota->sz < esz)
  1368. esz = quota->sz;
  1369. quota->esz = esz;
  1370. }
  1371. static void damos_adjust_quota(struct damon_ctx *c, struct damos *s)
  1372. {
  1373. struct damos_quota *quota = &s->quota;
  1374. struct damon_target *t;
  1375. struct damon_region *r;
  1376. unsigned long cumulated_sz;
  1377. unsigned int score, max_score = 0;
  1378. if (!quota->ms && !quota->sz && list_empty(&quota->goals))
  1379. return;
  1380. /* New charge window starts */
  1381. if (time_after_eq(jiffies, quota->charged_from +
  1382. msecs_to_jiffies(quota->reset_interval))) {
  1383. if (quota->esz && quota->charged_sz >= quota->esz)
  1384. s->stat.qt_exceeds++;
  1385. quota->total_charged_sz += quota->charged_sz;
  1386. quota->charged_from = jiffies;
  1387. quota->charged_sz = 0;
  1388. damos_set_effective_quota(quota);
  1389. }
  1390. if (!c->ops.get_scheme_score)
  1391. return;
  1392. /* Fill up the score histogram */
  1393. memset(c->regions_score_histogram, 0,
  1394. sizeof(*c->regions_score_histogram) *
  1395. (DAMOS_MAX_SCORE + 1));
  1396. damon_for_each_target(t, c) {
  1397. damon_for_each_region(r, t) {
  1398. if (!__damos_valid_target(r, s))
  1399. continue;
  1400. score = c->ops.get_scheme_score(c, t, r, s);
  1401. c->regions_score_histogram[score] +=
  1402. damon_sz_region(r);
  1403. if (score > max_score)
  1404. max_score = score;
  1405. }
  1406. }
  1407. /* Set the min score limit */
  1408. for (cumulated_sz = 0, score = max_score; ; score--) {
  1409. cumulated_sz += c->regions_score_histogram[score];
  1410. if (cumulated_sz >= quota->esz || !score)
  1411. break;
  1412. }
  1413. quota->min_score = score;
  1414. }
  1415. static void kdamond_apply_schemes(struct damon_ctx *c)
  1416. {
  1417. struct damon_target *t;
  1418. struct damon_region *r, *next_r;
  1419. struct damos *s;
  1420. unsigned long sample_interval = c->attrs.sample_interval ?
  1421. c->attrs.sample_interval : 1;
  1422. bool has_schemes_to_apply = false;
  1423. damon_for_each_scheme(s, c) {
  1424. if (c->passed_sample_intervals < s->next_apply_sis)
  1425. continue;
  1426. if (!s->wmarks.activated)
  1427. continue;
  1428. has_schemes_to_apply = true;
  1429. damos_adjust_quota(c, s);
  1430. }
  1431. if (!has_schemes_to_apply)
  1432. return;
  1433. damon_for_each_target(t, c) {
  1434. damon_for_each_region_safe(r, next_r, t)
  1435. damon_do_apply_schemes(c, t, r);
  1436. }
  1437. damon_for_each_scheme(s, c) {
  1438. if (c->passed_sample_intervals < s->next_apply_sis)
  1439. continue;
  1440. s->next_apply_sis = c->passed_sample_intervals +
  1441. (s->apply_interval_us ? s->apply_interval_us :
  1442. c->attrs.aggr_interval) / sample_interval;
  1443. }
  1444. }
  1445. /*
  1446. * Merge two adjacent regions into one region
  1447. */
  1448. static void damon_merge_two_regions(struct damon_target *t,
  1449. struct damon_region *l, struct damon_region *r)
  1450. {
  1451. unsigned long sz_l = damon_sz_region(l), sz_r = damon_sz_region(r);
  1452. l->nr_accesses = (l->nr_accesses * sz_l + r->nr_accesses * sz_r) /
  1453. (sz_l + sz_r);
  1454. l->nr_accesses_bp = l->nr_accesses * 10000;
  1455. l->age = (l->age * sz_l + r->age * sz_r) / (sz_l + sz_r);
  1456. l->ar.end = r->ar.end;
  1457. damon_destroy_region(r, t);
  1458. }
  1459. /*
  1460. * Merge adjacent regions having similar access frequencies
  1461. *
  1462. * t target affected by this merge operation
  1463. * thres '->nr_accesses' diff threshold for the merge
  1464. * sz_limit size upper limit of each region
  1465. */
  1466. static void damon_merge_regions_of(struct damon_target *t, unsigned int thres,
  1467. unsigned long sz_limit)
  1468. {
  1469. struct damon_region *r, *prev = NULL, *next;
  1470. damon_for_each_region_safe(r, next, t) {
  1471. if (abs(r->nr_accesses - r->last_nr_accesses) > thres)
  1472. r->age = 0;
  1473. else
  1474. r->age++;
  1475. if (prev && prev->ar.end == r->ar.start &&
  1476. abs(prev->nr_accesses - r->nr_accesses) <= thres &&
  1477. damon_sz_region(prev) + damon_sz_region(r) <= sz_limit)
  1478. damon_merge_two_regions(t, prev, r);
  1479. else
  1480. prev = r;
  1481. }
  1482. }
  1483. /*
  1484. * Merge adjacent regions having similar access frequencies
  1485. *
  1486. * threshold '->nr_accesses' diff threshold for the merge
  1487. * sz_limit size upper limit of each region
  1488. *
  1489. * This function merges monitoring target regions which are adjacent and their
  1490. * access frequencies are similar. This is for minimizing the monitoring
  1491. * overhead under the dynamically changeable access pattern. If a merge was
  1492. * unnecessarily made, later 'kdamond_split_regions()' will revert it.
  1493. *
  1494. * The total number of regions could be higher than the user-defined limit,
  1495. * max_nr_regions for some cases. For example, the user can update
  1496. * max_nr_regions to a number that lower than the current number of regions
  1497. * while DAMON is running. For such a case, repeat merging until the limit is
  1498. * met while increasing @threshold up to possible maximum level.
  1499. */
  1500. static void kdamond_merge_regions(struct damon_ctx *c, unsigned int threshold,
  1501. unsigned long sz_limit)
  1502. {
  1503. struct damon_target *t;
  1504. unsigned int nr_regions;
  1505. unsigned int max_thres;
  1506. max_thres = c->attrs.aggr_interval /
  1507. (c->attrs.sample_interval ? c->attrs.sample_interval : 1);
  1508. do {
  1509. nr_regions = 0;
  1510. damon_for_each_target(t, c) {
  1511. damon_merge_regions_of(t, threshold, sz_limit);
  1512. nr_regions += damon_nr_regions(t);
  1513. }
  1514. threshold = max(1, threshold * 2);
  1515. } while (nr_regions > c->attrs.max_nr_regions &&
  1516. threshold / 2 < max_thres);
  1517. }
  1518. /*
  1519. * Split a region in two
  1520. *
  1521. * r the region to be split
  1522. * sz_r size of the first sub-region that will be made
  1523. */
  1524. static void damon_split_region_at(struct damon_target *t,
  1525. struct damon_region *r, unsigned long sz_r)
  1526. {
  1527. struct damon_region *new;
  1528. new = damon_new_region(r->ar.start + sz_r, r->ar.end);
  1529. if (!new)
  1530. return;
  1531. r->ar.end = new->ar.start;
  1532. new->age = r->age;
  1533. new->last_nr_accesses = r->last_nr_accesses;
  1534. new->nr_accesses_bp = r->nr_accesses_bp;
  1535. new->nr_accesses = r->nr_accesses;
  1536. damon_insert_region(new, r, damon_next_region(r), t);
  1537. }
  1538. /* Split every region in the given target into 'nr_subs' regions */
  1539. static void damon_split_regions_of(struct damon_target *t, int nr_subs)
  1540. {
  1541. struct damon_region *r, *next;
  1542. unsigned long sz_region, sz_sub = 0;
  1543. int i;
  1544. damon_for_each_region_safe(r, next, t) {
  1545. sz_region = damon_sz_region(r);
  1546. for (i = 0; i < nr_subs - 1 &&
  1547. sz_region > 2 * DAMON_MIN_REGION; i++) {
  1548. /*
  1549. * Randomly select size of left sub-region to be at
  1550. * least 10 percent and at most 90% of original region
  1551. */
  1552. sz_sub = ALIGN_DOWN(damon_rand(1, 10) *
  1553. sz_region / 10, DAMON_MIN_REGION);
  1554. /* Do not allow blank region */
  1555. if (sz_sub == 0 || sz_sub >= sz_region)
  1556. continue;
  1557. damon_split_region_at(t, r, sz_sub);
  1558. sz_region = sz_sub;
  1559. }
  1560. }
  1561. }
  1562. /*
  1563. * Split every target region into randomly-sized small regions
  1564. *
  1565. * This function splits every target region into random-sized small regions if
  1566. * current total number of the regions is equal or smaller than half of the
  1567. * user-specified maximum number of regions. This is for maximizing the
  1568. * monitoring accuracy under the dynamically changeable access patterns. If a
  1569. * split was unnecessarily made, later 'kdamond_merge_regions()' will revert
  1570. * it.
  1571. */
  1572. static void kdamond_split_regions(struct damon_ctx *ctx)
  1573. {
  1574. struct damon_target *t;
  1575. unsigned int nr_regions = 0;
  1576. static unsigned int last_nr_regions;
  1577. int nr_subregions = 2;
  1578. damon_for_each_target(t, ctx)
  1579. nr_regions += damon_nr_regions(t);
  1580. if (nr_regions > ctx->attrs.max_nr_regions / 2)
  1581. return;
  1582. /* Maybe the middle of the region has different access frequency */
  1583. if (last_nr_regions == nr_regions &&
  1584. nr_regions < ctx->attrs.max_nr_regions / 3)
  1585. nr_subregions = 3;
  1586. damon_for_each_target(t, ctx)
  1587. damon_split_regions_of(t, nr_subregions);
  1588. last_nr_regions = nr_regions;
  1589. }
  1590. /*
  1591. * Check whether current monitoring should be stopped
  1592. *
  1593. * The monitoring is stopped when either the user requested to stop, or all
  1594. * monitoring targets are invalid.
  1595. *
  1596. * Returns true if need to stop current monitoring.
  1597. */
  1598. static bool kdamond_need_stop(struct damon_ctx *ctx)
  1599. {
  1600. struct damon_target *t;
  1601. if (kthread_should_stop())
  1602. return true;
  1603. if (!ctx->ops.target_valid)
  1604. return false;
  1605. damon_for_each_target(t, ctx) {
  1606. if (ctx->ops.target_valid(t))
  1607. return false;
  1608. }
  1609. return true;
  1610. }
  1611. static int damos_get_wmark_metric_value(enum damos_wmark_metric metric,
  1612. unsigned long *metric_value)
  1613. {
  1614. switch (metric) {
  1615. case DAMOS_WMARK_FREE_MEM_RATE:
  1616. *metric_value = global_zone_page_state(NR_FREE_PAGES) * 1000 /
  1617. totalram_pages();
  1618. return 0;
  1619. default:
  1620. break;
  1621. }
  1622. return -EINVAL;
  1623. }
  1624. /*
  1625. * Returns zero if the scheme is active. Else, returns time to wait for next
  1626. * watermark check in micro-seconds.
  1627. */
  1628. static unsigned long damos_wmark_wait_us(struct damos *scheme)
  1629. {
  1630. unsigned long metric;
  1631. if (damos_get_wmark_metric_value(scheme->wmarks.metric, &metric))
  1632. return 0;
  1633. /* higher than high watermark or lower than low watermark */
  1634. if (metric > scheme->wmarks.high || scheme->wmarks.low > metric) {
  1635. if (scheme->wmarks.activated)
  1636. pr_debug("deactivate a scheme (%d) for %s wmark\n",
  1637. scheme->action,
  1638. metric > scheme->wmarks.high ?
  1639. "high" : "low");
  1640. scheme->wmarks.activated = false;
  1641. return scheme->wmarks.interval;
  1642. }
  1643. /* inactive and higher than middle watermark */
  1644. if ((scheme->wmarks.high >= metric && metric >= scheme->wmarks.mid) &&
  1645. !scheme->wmarks.activated)
  1646. return scheme->wmarks.interval;
  1647. if (!scheme->wmarks.activated)
  1648. pr_debug("activate a scheme (%d)\n", scheme->action);
  1649. scheme->wmarks.activated = true;
  1650. return 0;
  1651. }
  1652. static void kdamond_usleep(unsigned long usecs)
  1653. {
  1654. /* See Documentation/timers/timers-howto.rst for the thresholds */
  1655. if (usecs > 20 * USEC_PER_MSEC)
  1656. schedule_timeout_idle(usecs_to_jiffies(usecs));
  1657. else
  1658. usleep_idle_range(usecs, usecs + 1);
  1659. }
  1660. /* Returns negative error code if it's not activated but should return */
  1661. static int kdamond_wait_activation(struct damon_ctx *ctx)
  1662. {
  1663. struct damos *s;
  1664. unsigned long wait_time;
  1665. unsigned long min_wait_time = 0;
  1666. bool init_wait_time = false;
  1667. while (!kdamond_need_stop(ctx)) {
  1668. damon_for_each_scheme(s, ctx) {
  1669. wait_time = damos_wmark_wait_us(s);
  1670. if (!init_wait_time || wait_time < min_wait_time) {
  1671. init_wait_time = true;
  1672. min_wait_time = wait_time;
  1673. }
  1674. }
  1675. if (!min_wait_time)
  1676. return 0;
  1677. kdamond_usleep(min_wait_time);
  1678. if (ctx->callback.after_wmarks_check &&
  1679. ctx->callback.after_wmarks_check(ctx))
  1680. break;
  1681. }
  1682. return -EBUSY;
  1683. }
  1684. static void kdamond_init_intervals_sis(struct damon_ctx *ctx)
  1685. {
  1686. unsigned long sample_interval = ctx->attrs.sample_interval ?
  1687. ctx->attrs.sample_interval : 1;
  1688. unsigned long apply_interval;
  1689. struct damos *scheme;
  1690. ctx->passed_sample_intervals = 0;
  1691. ctx->next_aggregation_sis = ctx->attrs.aggr_interval / sample_interval;
  1692. ctx->next_ops_update_sis = ctx->attrs.ops_update_interval /
  1693. sample_interval;
  1694. damon_for_each_scheme(scheme, ctx) {
  1695. apply_interval = scheme->apply_interval_us ?
  1696. scheme->apply_interval_us : ctx->attrs.aggr_interval;
  1697. scheme->next_apply_sis = apply_interval / sample_interval;
  1698. }
  1699. }
  1700. /*
  1701. * The monitoring daemon that runs as a kernel thread
  1702. */
  1703. static int kdamond_fn(void *data)
  1704. {
  1705. struct damon_ctx *ctx = data;
  1706. struct damon_target *t;
  1707. struct damon_region *r, *next;
  1708. unsigned int max_nr_accesses = 0;
  1709. unsigned long sz_limit = 0;
  1710. pr_debug("kdamond (%d) starts\n", current->pid);
  1711. complete(&ctx->kdamond_started);
  1712. kdamond_init_intervals_sis(ctx);
  1713. if (ctx->ops.init)
  1714. ctx->ops.init(ctx);
  1715. if (ctx->callback.before_start && ctx->callback.before_start(ctx))
  1716. goto done;
  1717. ctx->regions_score_histogram = kmalloc_array(DAMOS_MAX_SCORE + 1,
  1718. sizeof(*ctx->regions_score_histogram), GFP_KERNEL);
  1719. if (!ctx->regions_score_histogram)
  1720. goto done;
  1721. sz_limit = damon_region_sz_limit(ctx);
  1722. while (!kdamond_need_stop(ctx)) {
  1723. /*
  1724. * ctx->attrs and ctx->next_{aggregation,ops_update}_sis could
  1725. * be changed from after_wmarks_check() or after_aggregation()
  1726. * callbacks. Read the values here, and use those for this
  1727. * iteration. That is, damon_set_attrs() updated new values
  1728. * are respected from next iteration.
  1729. */
  1730. unsigned long next_aggregation_sis = ctx->next_aggregation_sis;
  1731. unsigned long next_ops_update_sis = ctx->next_ops_update_sis;
  1732. unsigned long sample_interval = ctx->attrs.sample_interval;
  1733. if (kdamond_wait_activation(ctx))
  1734. break;
  1735. if (ctx->ops.prepare_access_checks)
  1736. ctx->ops.prepare_access_checks(ctx);
  1737. if (ctx->callback.after_sampling &&
  1738. ctx->callback.after_sampling(ctx))
  1739. break;
  1740. kdamond_usleep(sample_interval);
  1741. ctx->passed_sample_intervals++;
  1742. if (ctx->ops.check_accesses)
  1743. max_nr_accesses = ctx->ops.check_accesses(ctx);
  1744. if (ctx->passed_sample_intervals >= next_aggregation_sis) {
  1745. kdamond_merge_regions(ctx,
  1746. max_nr_accesses / 10,
  1747. sz_limit);
  1748. if (ctx->callback.after_aggregation &&
  1749. ctx->callback.after_aggregation(ctx))
  1750. break;
  1751. }
  1752. /*
  1753. * do kdamond_apply_schemes() after kdamond_merge_regions() if
  1754. * possible, to reduce overhead
  1755. */
  1756. if (!list_empty(&ctx->schemes))
  1757. kdamond_apply_schemes(ctx);
  1758. sample_interval = ctx->attrs.sample_interval ?
  1759. ctx->attrs.sample_interval : 1;
  1760. if (ctx->passed_sample_intervals >= next_aggregation_sis) {
  1761. ctx->next_aggregation_sis = next_aggregation_sis +
  1762. ctx->attrs.aggr_interval / sample_interval;
  1763. kdamond_reset_aggregated(ctx);
  1764. kdamond_split_regions(ctx);
  1765. if (ctx->ops.reset_aggregated)
  1766. ctx->ops.reset_aggregated(ctx);
  1767. }
  1768. if (ctx->passed_sample_intervals >= next_ops_update_sis) {
  1769. ctx->next_ops_update_sis = next_ops_update_sis +
  1770. ctx->attrs.ops_update_interval /
  1771. sample_interval;
  1772. if (ctx->ops.update)
  1773. ctx->ops.update(ctx);
  1774. sz_limit = damon_region_sz_limit(ctx);
  1775. }
  1776. }
  1777. done:
  1778. damon_for_each_target(t, ctx) {
  1779. damon_for_each_region_safe(r, next, t)
  1780. damon_destroy_region(r, t);
  1781. }
  1782. if (ctx->callback.before_terminate)
  1783. ctx->callback.before_terminate(ctx);
  1784. if (ctx->ops.cleanup)
  1785. ctx->ops.cleanup(ctx);
  1786. kfree(ctx->regions_score_histogram);
  1787. pr_debug("kdamond (%d) finishes\n", current->pid);
  1788. mutex_lock(&ctx->kdamond_lock);
  1789. ctx->kdamond = NULL;
  1790. mutex_unlock(&ctx->kdamond_lock);
  1791. mutex_lock(&damon_lock);
  1792. nr_running_ctxs--;
  1793. if (!nr_running_ctxs && running_exclusive_ctxs)
  1794. running_exclusive_ctxs = false;
  1795. mutex_unlock(&damon_lock);
  1796. return 0;
  1797. }
  1798. /*
  1799. * struct damon_system_ram_region - System RAM resource address region of
  1800. * [@start, @end).
  1801. * @start: Start address of the region (inclusive).
  1802. * @end: End address of the region (exclusive).
  1803. */
  1804. struct damon_system_ram_region {
  1805. unsigned long start;
  1806. unsigned long end;
  1807. };
  1808. static int walk_system_ram(struct resource *res, void *arg)
  1809. {
  1810. struct damon_system_ram_region *a = arg;
  1811. if (a->end - a->start < resource_size(res)) {
  1812. a->start = res->start;
  1813. a->end = res->end;
  1814. }
  1815. return 0;
  1816. }
  1817. /*
  1818. * Find biggest 'System RAM' resource and store its start and end address in
  1819. * @start and @end, respectively. If no System RAM is found, returns false.
  1820. */
  1821. static bool damon_find_biggest_system_ram(unsigned long *start,
  1822. unsigned long *end)
  1823. {
  1824. struct damon_system_ram_region arg = {};
  1825. walk_system_ram_res(0, ULONG_MAX, &arg, walk_system_ram);
  1826. if (arg.end <= arg.start)
  1827. return false;
  1828. *start = arg.start;
  1829. *end = arg.end;
  1830. return true;
  1831. }
  1832. /**
  1833. * damon_set_region_biggest_system_ram_default() - Set the region of the given
  1834. * monitoring target as requested, or biggest 'System RAM'.
  1835. * @t: The monitoring target to set the region.
  1836. * @start: The pointer to the start address of the region.
  1837. * @end: The pointer to the end address of the region.
  1838. *
  1839. * This function sets the region of @t as requested by @start and @end. If the
  1840. * values of @start and @end are zero, however, this function finds the biggest
  1841. * 'System RAM' resource and sets the region to cover the resource. In the
  1842. * latter case, this function saves the start and end addresses of the resource
  1843. * in @start and @end, respectively.
  1844. *
  1845. * Return: 0 on success, negative error code otherwise.
  1846. */
  1847. int damon_set_region_biggest_system_ram_default(struct damon_target *t,
  1848. unsigned long *start, unsigned long *end)
  1849. {
  1850. struct damon_addr_range addr_range;
  1851. if (*start > *end)
  1852. return -EINVAL;
  1853. if (!*start && !*end &&
  1854. !damon_find_biggest_system_ram(start, end))
  1855. return -EINVAL;
  1856. addr_range.start = *start;
  1857. addr_range.end = *end;
  1858. return damon_set_regions(t, &addr_range, 1);
  1859. }
  1860. /*
  1861. * damon_moving_sum() - Calculate an inferred moving sum value.
  1862. * @mvsum: Inferred sum of the last @len_window values.
  1863. * @nomvsum: Non-moving sum of the last discrete @len_window window values.
  1864. * @len_window: The number of last values to take care of.
  1865. * @new_value: New value that will be added to the pseudo moving sum.
  1866. *
  1867. * Moving sum (moving average * window size) is good for handling noise, but
  1868. * the cost of keeping past values can be high for arbitrary window size. This
  1869. * function implements a lightweight pseudo moving sum function that doesn't
  1870. * keep the past window values.
  1871. *
  1872. * It simply assumes there was no noise in the past, and get the no-noise
  1873. * assumed past value to drop from @nomvsum and @len_window. @nomvsum is a
  1874. * non-moving sum of the last window. For example, if @len_window is 10 and we
  1875. * have 25 values, @nomvsum is the sum of the 11th to 20th values of the 25
  1876. * values. Hence, this function simply drops @nomvsum / @len_window from
  1877. * given @mvsum and add @new_value.
  1878. *
  1879. * For example, if @len_window is 10 and @nomvsum is 50, the last 10 values for
  1880. * the last window could be vary, e.g., 0, 10, 0, 10, 0, 10, 0, 0, 0, 20. For
  1881. * calculating next moving sum with a new value, we should drop 0 from 50 and
  1882. * add the new value. However, this function assumes it got value 5 for each
  1883. * of the last ten times. Based on the assumption, when the next value is
  1884. * measured, it drops the assumed past value, 5 from the current sum, and add
  1885. * the new value to get the updated pseduo-moving average.
  1886. *
  1887. * This means the value could have errors, but the errors will be disappeared
  1888. * for every @len_window aligned calls. For example, if @len_window is 10, the
  1889. * pseudo moving sum with 11th value to 19th value would have an error. But
  1890. * the sum with 20th value will not have the error.
  1891. *
  1892. * Return: Pseudo-moving average after getting the @new_value.
  1893. */
  1894. static unsigned int damon_moving_sum(unsigned int mvsum, unsigned int nomvsum,
  1895. unsigned int len_window, unsigned int new_value)
  1896. {
  1897. return mvsum - nomvsum / len_window + new_value;
  1898. }
  1899. /**
  1900. * damon_update_region_access_rate() - Update the access rate of a region.
  1901. * @r: The DAMON region to update for its access check result.
  1902. * @accessed: Whether the region has accessed during last sampling interval.
  1903. * @attrs: The damon_attrs of the DAMON context.
  1904. *
  1905. * Update the access rate of a region with the region's last sampling interval
  1906. * access check result.
  1907. *
  1908. * Usually this will be called by &damon_operations->check_accesses callback.
  1909. */
  1910. void damon_update_region_access_rate(struct damon_region *r, bool accessed,
  1911. struct damon_attrs *attrs)
  1912. {
  1913. unsigned int len_window = 1;
  1914. /*
  1915. * sample_interval can be zero, but cannot be larger than
  1916. * aggr_interval, owing to validation of damon_set_attrs().
  1917. */
  1918. if (attrs->sample_interval)
  1919. len_window = damon_max_nr_accesses(attrs);
  1920. r->nr_accesses_bp = damon_moving_sum(r->nr_accesses_bp,
  1921. r->last_nr_accesses * 10000, len_window,
  1922. accessed ? 10000 : 0);
  1923. if (accessed)
  1924. r->nr_accesses++;
  1925. }
  1926. static int __init damon_init(void)
  1927. {
  1928. damon_region_cache = KMEM_CACHE(damon_region, 0);
  1929. if (unlikely(!damon_region_cache)) {
  1930. pr_err("creating damon_region_cache fails\n");
  1931. return -ENOMEM;
  1932. }
  1933. return 0;
  1934. }
  1935. subsys_initcall(damon_init);
  1936. #include "tests/core-kunit.h"