dictionary.c 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. #define DICTIONARY_INTERNALS
  3. #include "../libnetdata.h"
  4. // runtime flags of the dictionary - must be checked with atomics
  5. typedef enum __attribute__ ((__packed__)) {
  6. DICT_FLAG_NONE = 0,
  7. DICT_FLAG_DESTROYED = (1 << 0), // this dictionary has been destroyed
  8. } DICT_FLAGS;
  9. #define dict_flag_check(dict, flag) (__atomic_load_n(&((dict)->flags), __ATOMIC_RELAXED) & (flag))
  10. #define dict_flag_set(dict, flag) __atomic_or_fetch(&((dict)->flags), flag, __ATOMIC_RELAXED)
  11. #define dict_flag_clear(dict, flag) __atomic_and_fetch(&((dict)->flags), ~(flag), __ATOMIC_RELAXED)
  12. // flags macros
  13. #define is_dictionary_destroyed(dict) dict_flag_check(dict, DICT_FLAG_DESTROYED)
  14. // configuration options macros
  15. #define is_dictionary_single_threaded(dict) ((dict)->options & DICT_OPTION_SINGLE_THREADED)
  16. #define is_view_dictionary(dict) ((dict)->master)
  17. #define is_master_dictionary(dict) (!is_view_dictionary(dict))
  18. typedef enum __attribute__ ((__packed__)) item_options {
  19. ITEM_OPTION_NONE = 0,
  20. ITEM_OPTION_ALLOCATED_NAME = (1 << 0), // the name pointer is a STRING
  21. // IMPORTANT: This is 1-bit - to add more change ITEM_OPTIONS_BITS
  22. } ITEM_OPTIONS;
  23. typedef enum __attribute__ ((__packed__)) item_flags {
  24. ITEM_FLAG_NONE = 0,
  25. ITEM_FLAG_DELETED = (1 << 0), // this item is marked deleted, so it is not available for traversal (deleted from the index too)
  26. ITEM_FLAG_BEING_CREATED = (1 << 1), // this item is currently being created - this flag is removed when construction finishes
  27. // IMPORTANT: This is 8-bit
  28. } ITEM_FLAGS;
  29. #define item_flag_check(item, flag) (__atomic_load_n(&((item)->flags), __ATOMIC_RELAXED) & (flag))
  30. #define item_flag_set(item, flag) __atomic_or_fetch(&((item)->flags), flag, __ATOMIC_RELAXED)
  31. #define item_flag_clear(item, flag) __atomic_and_fetch(&((item)->flags), ~(flag), __ATOMIC_RELAXED)
  32. #define item_shared_flag_check(item, flag) (__atomic_load_n(&((item)->shared->flags), __ATOMIC_RELAXED) & (flag))
  33. #define item_shared_flag_set(item, flag) __atomic_or_fetch(&((item)->shared->flags), flag, __ATOMIC_RELAXED)
  34. #define item_shared_flag_clear(item, flag) __atomic_and_fetch(&((item)->shared->flags), ~(flag), __ATOMIC_RELAXED)
  35. #define REFCOUNT_DELETING (-100)
  36. #define ITEM_FLAGS_TYPE uint8_t
  37. #define KEY_LEN_TYPE uint32_t
  38. #define VALUE_LEN_TYPE uint32_t
  39. #define ITEM_OPTIONS_BITS 1
  40. #define KEY_LEN_BITS ((sizeof(KEY_LEN_TYPE) * 8) - (sizeof(ITEM_FLAGS_TYPE) * 8) - ITEM_OPTIONS_BITS)
  41. #define KEY_LEN_MAX ((1 << KEY_LEN_BITS) - 1)
  42. #define VALUE_LEN_BITS ((sizeof(VALUE_LEN_TYPE) * 8) - (sizeof(ITEM_FLAGS_TYPE) * 8))
  43. #define VALUE_LEN_MAX ((1 << VALUE_LEN_BITS) - 1)
  44. /*
  45. * Every item in the dictionary has the following structure.
  46. */
  47. typedef int32_t REFCOUNT;
  48. typedef struct dictionary_item_shared {
  49. void *value; // the value of the dictionary item
  50. // the order of the following items is important!
  51. // The total of their storage should be 64-bits
  52. REFCOUNT links; // how many links this item has
  53. VALUE_LEN_TYPE value_len:VALUE_LEN_BITS; // the size of the value
  54. ITEM_FLAGS_TYPE flags; // shared flags
  55. } DICTIONARY_ITEM_SHARED;
  56. struct dictionary_item {
  57. #ifdef NETDATA_INTERNAL_CHECKS
  58. DICTIONARY *dict;
  59. pid_t creator_pid;
  60. pid_t deleter_pid;
  61. pid_t ll_adder_pid;
  62. pid_t ll_remover_pid;
  63. #endif
  64. DICTIONARY_ITEM_SHARED *shared;
  65. struct dictionary_item *next; // a double linked list to allow fast insertions and deletions
  66. struct dictionary_item *prev;
  67. union {
  68. STRING *string_name; // the name of the dictionary item
  69. char *caller_name; // the user supplied string pointer
  70. // void *key_ptr; // binary key pointer
  71. };
  72. // the order of the following items is important!
  73. // The total of their storage should be 64-bits
  74. REFCOUNT refcount; // the private reference counter
  75. KEY_LEN_TYPE key_len:KEY_LEN_BITS; // the size of key indexed (for strings, including the null terminator)
  76. // this is (2^23 - 1) = 8.388.607 bytes max key length.
  77. ITEM_OPTIONS options:ITEM_OPTIONS_BITS; // permanent configuration options
  78. // (no atomic operations on this - they never change)
  79. ITEM_FLAGS_TYPE flags; // runtime changing flags for this item (atomic operations on this)
  80. // cannot be a bit field because of atomics.
  81. };
  82. struct dictionary_hooks {
  83. REFCOUNT links;
  84. usec_t last_master_deletion_us;
  85. void (*ins_callback)(const DICTIONARY_ITEM *item, void *value, void *data);
  86. void *ins_callback_data;
  87. bool (*conflict_callback)(const DICTIONARY_ITEM *item, void *old_value, void *new_value, void *data);
  88. void *conflict_callback_data;
  89. void (*react_callback)(const DICTIONARY_ITEM *item, void *value, void *data);
  90. void *react_callback_data;
  91. void (*del_callback)(const DICTIONARY_ITEM *item, void *value, void *data);
  92. void *del_callback_data;
  93. };
  94. struct dictionary_stats dictionary_stats_category_other = {
  95. .name = "other",
  96. };
  97. struct dictionary {
  98. #ifdef NETDATA_INTERNAL_CHECKS
  99. const char *creation_function;
  100. const char *creation_file;
  101. size_t creation_line;
  102. pid_t creation_tid;
  103. #endif
  104. usec_t last_gc_run_us;
  105. DICT_OPTIONS options; // the configuration flags of the dictionary (they never change - no atomics)
  106. DICT_FLAGS flags; // run time flags for the dictionary (they change all the time - atomics needed)
  107. ARAL *value_aral;
  108. struct { // support for multiple indexing engines
  109. Pvoid_t JudyHSArray; // the hash table
  110. RW_SPINLOCK rw_spinlock; // protect the index
  111. } index;
  112. struct {
  113. DICTIONARY_ITEM *list; // the double linked list of all items in the dictionary
  114. RW_SPINLOCK rw_spinlock; // protect the linked-list
  115. pid_t writer_pid; // the gettid() of the writer
  116. uint32_t writer_depth; // nesting of write locks
  117. } items;
  118. struct dictionary_hooks *hooks; // pointer to external function callbacks to be called at certain points
  119. struct dictionary_stats *stats; // statistics data, when DICT_OPTION_STATS is set
  120. DICTIONARY *master; // the master dictionary
  121. DICTIONARY *next; // linked list for delayed destruction (garbage collection of whole dictionaries)
  122. uint32_t version; // the current version of the dictionary
  123. // it is incremented when:
  124. // - item added
  125. // - item removed
  126. // - item value reset
  127. // - conflict callback returns true
  128. // - function dictionary_version_increment() is called
  129. int32_t entries; // how many items are currently in the index (the linked list may have more)
  130. int32_t referenced_items; // how many items of the dictionary are currently being used by 3rd parties
  131. int32_t pending_deletion_items; // how many items of the dictionary have been deleted, but have not been removed yet
  132. #ifdef NETDATA_DICTIONARY_VALIDATE_POINTERS
  133. netdata_mutex_t global_pointer_registry_mutex;
  134. Pvoid_t global_pointer_registry;
  135. #endif
  136. };
  137. // ----------------------------------------------------------------------------
  138. // forward definitions of functions used in reverse order in the code
  139. static void garbage_collect_pending_deletes(DICTIONARY *dict);
  140. static inline void item_linked_list_remove(DICTIONARY *dict, DICTIONARY_ITEM *item);
  141. static size_t dict_item_free_with_hooks(DICTIONARY *dict, DICTIONARY_ITEM *item);
  142. static inline const char *item_get_name(const DICTIONARY_ITEM *item);
  143. static inline int hashtable_delete_unsafe(DICTIONARY *dict, const char *name, size_t name_len, void *item);
  144. static void item_release(DICTIONARY *dict, DICTIONARY_ITEM *item);
  145. static bool dict_item_set_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item);
  146. #define RC_ITEM_OK ( 0)
  147. #define RC_ITEM_MARKED_FOR_DELETION (-1) // the item is marked for deletion
  148. #define RC_ITEM_IS_CURRENTLY_BEING_DELETED (-2) // the item is currently being deleted
  149. #define RC_ITEM_IS_CURRENTLY_BEING_CREATED (-3) // the item is currently being deleted
  150. #define RC_ITEM_IS_REFERENCED (-4) // the item is currently referenced
  151. #define item_check_and_acquire(dict, item) (item_check_and_acquire_advanced(dict, item, false) == RC_ITEM_OK)
  152. static int item_check_and_acquire_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item, bool having_index_lock);
  153. #define item_is_not_referenced_and_can_be_removed(dict, item) (item_is_not_referenced_and_can_be_removed_advanced(dict, item) == RC_ITEM_OK)
  154. static inline int item_is_not_referenced_and_can_be_removed_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item);
  155. // ----------------------------------------------------------------------------
  156. // validate each pointer is indexed once - internal checks only
  157. #ifdef NETDATA_DICTIONARY_VALIDATE_POINTERS
  158. static inline void pointer_index_init(DICTIONARY *dict __maybe_unused) {
  159. netdata_mutex_init(&dict->global_pointer_registry_mutex);
  160. }
  161. static inline void pointer_destroy_index(DICTIONARY *dict __maybe_unused) {
  162. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  163. JudyHSFreeArray(&dict->global_pointer_registry, PJE0);
  164. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  165. }
  166. static inline void pointer_add(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item __maybe_unused) {
  167. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  168. Pvoid_t *PValue = JudyHSIns(&dict->global_pointer_registry, &item, sizeof(void *), PJE0);
  169. if(*PValue != NULL)
  170. fatal("pointer already exists in registry");
  171. *PValue = item;
  172. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  173. }
  174. static inline void pointer_check(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item __maybe_unused) {
  175. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  176. Pvoid_t *PValue = JudyHSGet(dict->global_pointer_registry, &item, sizeof(void *));
  177. if(PValue == NULL)
  178. fatal("pointer is not found in registry");
  179. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  180. }
  181. static inline void pointer_del(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item __maybe_unused) {
  182. netdata_mutex_lock(&dict->global_pointer_registry_mutex);
  183. int ret = JudyHSDel(&dict->global_pointer_registry, &item, sizeof(void *), PJE0);
  184. if(!ret)
  185. fatal("pointer to be deleted does not exist in registry");
  186. netdata_mutex_unlock(&dict->global_pointer_registry_mutex);
  187. }
  188. #else // !NETDATA_DICTIONARY_VALIDATE_POINTERS
  189. #define pointer_index_init(dict) debug_dummy()
  190. #define pointer_destroy_index(dict) debug_dummy()
  191. #define pointer_add(dict, item) debug_dummy()
  192. #define pointer_check(dict, item) debug_dummy()
  193. #define pointer_del(dict, item) debug_dummy()
  194. #endif // !NETDATA_DICTIONARY_VALIDATE_POINTERS
  195. // ----------------------------------------------------------------------------
  196. // memory statistics
  197. #ifdef DICT_WITH_STATS
  198. static inline void DICTIONARY_STATS_PLUS_MEMORY(DICTIONARY *dict, size_t key_size, size_t item_size, size_t value_size) {
  199. if(key_size)
  200. __atomic_fetch_add(&dict->stats->memory.index, (long)JUDYHS_INDEX_SIZE_ESTIMATE(key_size), __ATOMIC_RELAXED);
  201. if(item_size)
  202. __atomic_fetch_add(&dict->stats->memory.dict, (long)item_size, __ATOMIC_RELAXED);
  203. if(value_size)
  204. __atomic_fetch_add(&dict->stats->memory.values, (long)value_size, __ATOMIC_RELAXED);
  205. }
  206. static inline void DICTIONARY_STATS_MINUS_MEMORY(DICTIONARY *dict, size_t key_size, size_t item_size, size_t value_size) {
  207. if(key_size)
  208. __atomic_fetch_sub(&dict->stats->memory.index, (long)JUDYHS_INDEX_SIZE_ESTIMATE(key_size), __ATOMIC_RELAXED);
  209. if(item_size)
  210. __atomic_fetch_sub(&dict->stats->memory.dict, (long)item_size, __ATOMIC_RELAXED);
  211. if(value_size)
  212. __atomic_fetch_sub(&dict->stats->memory.values, (long)value_size, __ATOMIC_RELAXED);
  213. }
  214. #else
  215. #define DICTIONARY_STATS_PLUS_MEMORY(dict, key_size, item_size, value_size) do {;} while(0)
  216. #define DICTIONARY_STATS_MINUS_MEMORY(dict, key_size, item_size, value_size) do {;} while(0)
  217. #endif
  218. // ----------------------------------------------------------------------------
  219. // callbacks registration
  220. static inline void dictionary_hooks_allocate(DICTIONARY *dict) {
  221. if(dict->hooks) return;
  222. dict->hooks = callocz(1, sizeof(struct dictionary_hooks));
  223. dict->hooks->links = 1;
  224. DICTIONARY_STATS_PLUS_MEMORY(dict, 0, sizeof(struct dictionary_hooks), 0);
  225. }
  226. static inline size_t dictionary_hooks_free(DICTIONARY *dict) {
  227. if(!dict->hooks) return 0;
  228. REFCOUNT links = __atomic_sub_fetch(&dict->hooks->links, 1, __ATOMIC_ACQUIRE);
  229. if(links == 0) {
  230. freez(dict->hooks);
  231. dict->hooks = NULL;
  232. DICTIONARY_STATS_MINUS_MEMORY(dict, 0, sizeof(struct dictionary_hooks), 0);
  233. return sizeof(struct dictionary_hooks);
  234. }
  235. return 0;
  236. }
  237. void dictionary_register_insert_callback(DICTIONARY *dict, void (*ins_callback)(const DICTIONARY_ITEM *item, void *value, void *data), void *data) {
  238. if(unlikely(is_view_dictionary(dict)))
  239. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  240. dictionary_hooks_allocate(dict);
  241. dict->hooks->ins_callback = ins_callback;
  242. dict->hooks->ins_callback_data = data;
  243. }
  244. void dictionary_register_conflict_callback(DICTIONARY *dict, bool (*conflict_callback)(const DICTIONARY_ITEM *item, void *old_value, void *new_value, void *data), void *data) {
  245. if(unlikely(is_view_dictionary(dict)))
  246. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  247. internal_error(!(dict->options & DICT_OPTION_DONT_OVERWRITE_VALUE), "DICTIONARY: registering conflict callback without DICT_OPTION_DONT_OVERWRITE_VALUE");
  248. dict->options |= DICT_OPTION_DONT_OVERWRITE_VALUE;
  249. dictionary_hooks_allocate(dict);
  250. dict->hooks->conflict_callback = conflict_callback;
  251. dict->hooks->conflict_callback_data = data;
  252. }
  253. void dictionary_register_react_callback(DICTIONARY *dict, void (*react_callback)(const DICTIONARY_ITEM *item, void *value, void *data), void *data) {
  254. if(unlikely(is_view_dictionary(dict)))
  255. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  256. dictionary_hooks_allocate(dict);
  257. dict->hooks->react_callback = react_callback;
  258. dict->hooks->react_callback_data = data;
  259. }
  260. void dictionary_register_delete_callback(DICTIONARY *dict, void (*del_callback)(const DICTIONARY_ITEM *item, void *value, void *data), void *data) {
  261. if(unlikely(is_view_dictionary(dict)))
  262. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  263. dictionary_hooks_allocate(dict);
  264. dict->hooks->del_callback = del_callback;
  265. dict->hooks->del_callback_data = data;
  266. }
  267. // ----------------------------------------------------------------------------
  268. // dictionary statistics API
  269. size_t dictionary_version(DICTIONARY *dict) {
  270. if(unlikely(!dict)) return 0;
  271. // this is required for views to return the right number
  272. // garbage_collect_pending_deletes(dict);
  273. return __atomic_load_n(&dict->version, __ATOMIC_RELAXED);
  274. }
  275. size_t dictionary_entries(DICTIONARY *dict) {
  276. if(unlikely(!dict)) return 0;
  277. // this is required for views to return the right number
  278. // garbage_collect_pending_deletes(dict);
  279. long int entries = __atomic_load_n(&dict->entries, __ATOMIC_RELAXED);
  280. internal_fatal(entries < 0, "DICTIONARY: entries is negative: %ld", entries);
  281. return entries;
  282. }
  283. size_t dictionary_referenced_items(DICTIONARY *dict) {
  284. if(unlikely(!dict)) return 0;
  285. long int referenced_items = __atomic_load_n(&dict->referenced_items, __ATOMIC_RELAXED);
  286. if(referenced_items < 0)
  287. fatal("DICTIONARY: referenced items is negative: %ld", referenced_items);
  288. return referenced_items;
  289. }
  290. void dictionary_version_increment(DICTIONARY *dict) {
  291. __atomic_fetch_add(&dict->version, 1, __ATOMIC_RELAXED);
  292. }
  293. // ----------------------------------------------------------------------------
  294. // internal statistics API
  295. #ifdef DICT_WITH_STATS
  296. static inline void DICTIONARY_STATS_SEARCHES_PLUS1(DICTIONARY *dict) {
  297. __atomic_fetch_add(&dict->stats->ops.searches, 1, __ATOMIC_RELAXED);
  298. }
  299. #else
  300. #define DICTIONARY_STATS_SEARCHES_PLUS1(dict) do {;} while(0)
  301. #endif
  302. static inline void DICTIONARY_ENTRIES_PLUS1(DICTIONARY *dict) {
  303. #ifdef DICT_WITH_STATS
  304. // statistics
  305. __atomic_fetch_add(&dict->stats->items.entries, 1, __ATOMIC_RELAXED);
  306. __atomic_fetch_add(&dict->stats->items.referenced, 1, __ATOMIC_RELAXED);
  307. __atomic_fetch_add(&dict->stats->ops.inserts, 1, __ATOMIC_RELAXED);
  308. #endif
  309. if(unlikely(is_dictionary_single_threaded(dict))) {
  310. dict->version++;
  311. dict->entries++;
  312. dict->referenced_items++;
  313. }
  314. else {
  315. __atomic_fetch_add(&dict->version, 1, __ATOMIC_RELAXED);
  316. __atomic_fetch_add(&dict->entries, 1, __ATOMIC_RELAXED);
  317. __atomic_fetch_add(&dict->referenced_items, 1, __ATOMIC_RELAXED);
  318. }
  319. }
  320. static inline void DICTIONARY_ENTRIES_MINUS1(DICTIONARY *dict) {
  321. #ifdef DICT_WITH_STATS
  322. // statistics
  323. __atomic_fetch_add(&dict->stats->ops.deletes, 1, __ATOMIC_RELAXED);
  324. __atomic_fetch_sub(&dict->stats->items.entries, 1, __ATOMIC_RELAXED);
  325. #endif
  326. size_t entries; (void)entries;
  327. if(unlikely(is_dictionary_single_threaded(dict))) {
  328. dict->version++;
  329. entries = dict->entries--;
  330. }
  331. else {
  332. __atomic_fetch_add(&dict->version, 1, __ATOMIC_RELAXED);
  333. entries = __atomic_fetch_sub(&dict->entries, 1, __ATOMIC_RELAXED);
  334. }
  335. internal_fatal(entries == 0,
  336. "DICT: negative number of entries in dictionary created from %s() (%zu@%s)",
  337. dict->creation_function,
  338. dict->creation_line,
  339. dict->creation_file);
  340. }
  341. static inline void DICTIONARY_VALUE_RESETS_PLUS1(DICTIONARY *dict) {
  342. #ifdef DICT_WITH_STATS
  343. __atomic_fetch_add(&dict->stats->ops.resets, 1, __ATOMIC_RELAXED);
  344. #endif
  345. if(unlikely(is_dictionary_single_threaded(dict)))
  346. dict->version++;
  347. else
  348. __atomic_fetch_add(&dict->version, 1, __ATOMIC_RELAXED);
  349. }
  350. #ifdef DICT_WITH_STATS
  351. static inline void DICTIONARY_STATS_TRAVERSALS_PLUS1(DICTIONARY *dict) {
  352. __atomic_fetch_add(&dict->stats->ops.traversals, 1, __ATOMIC_RELAXED);
  353. }
  354. static inline void DICTIONARY_STATS_WALKTHROUGHS_PLUS1(DICTIONARY *dict) {
  355. __atomic_fetch_add(&dict->stats->ops.walkthroughs, 1, __ATOMIC_RELAXED);
  356. }
  357. static inline void DICTIONARY_STATS_CHECK_SPINS_PLUS(DICTIONARY *dict, size_t count) {
  358. __atomic_fetch_add(&dict->stats->spin_locks.use_spins, count, __ATOMIC_RELAXED);
  359. }
  360. static inline void DICTIONARY_STATS_INSERT_SPINS_PLUS(DICTIONARY *dict, size_t count) {
  361. __atomic_fetch_add(&dict->stats->spin_locks.insert_spins, count, __ATOMIC_RELAXED);
  362. }
  363. static inline void DICTIONARY_STATS_DELETE_SPINS_PLUS(DICTIONARY *dict, size_t count) {
  364. __atomic_fetch_add(&dict->stats->spin_locks.delete_spins, count, __ATOMIC_RELAXED);
  365. }
  366. static inline void DICTIONARY_STATS_SEARCH_IGNORES_PLUS1(DICTIONARY *dict) {
  367. __atomic_fetch_add(&dict->stats->spin_locks.search_spins, 1, __ATOMIC_RELAXED);
  368. }
  369. static inline void DICTIONARY_STATS_CALLBACK_INSERTS_PLUS1(DICTIONARY *dict) {
  370. __atomic_fetch_add(&dict->stats->callbacks.inserts, 1, __ATOMIC_RELEASE);
  371. }
  372. static inline void DICTIONARY_STATS_CALLBACK_CONFLICTS_PLUS1(DICTIONARY *dict) {
  373. __atomic_fetch_add(&dict->stats->callbacks.conflicts, 1, __ATOMIC_RELEASE);
  374. }
  375. static inline void DICTIONARY_STATS_CALLBACK_REACTS_PLUS1(DICTIONARY *dict) {
  376. __atomic_fetch_add(&dict->stats->callbacks.reacts, 1, __ATOMIC_RELEASE);
  377. }
  378. static inline void DICTIONARY_STATS_CALLBACK_DELETES_PLUS1(DICTIONARY *dict) {
  379. __atomic_fetch_add(&dict->stats->callbacks.deletes, 1, __ATOMIC_RELEASE);
  380. }
  381. static inline void DICTIONARY_STATS_GARBAGE_COLLECTIONS_PLUS1(DICTIONARY *dict) {
  382. __atomic_fetch_add(&dict->stats->ops.garbage_collections, 1, __ATOMIC_RELAXED);
  383. }
  384. static inline void DICTIONARY_STATS_DICT_CREATIONS_PLUS1(DICTIONARY *dict) {
  385. __atomic_fetch_add(&dict->stats->dictionaries.active, 1, __ATOMIC_RELAXED);
  386. __atomic_fetch_add(&dict->stats->ops.creations, 1, __ATOMIC_RELAXED);
  387. }
  388. static inline void DICTIONARY_STATS_DICT_DESTRUCTIONS_PLUS1(DICTIONARY *dict) {
  389. __atomic_fetch_sub(&dict->stats->dictionaries.active, 1, __ATOMIC_RELAXED);
  390. __atomic_fetch_add(&dict->stats->ops.destructions, 1, __ATOMIC_RELAXED);
  391. }
  392. static inline void DICTIONARY_STATS_DICT_DESTROY_QUEUED_PLUS1(DICTIONARY *dict) {
  393. __atomic_fetch_add(&dict->stats->dictionaries.deleted, 1, __ATOMIC_RELAXED);
  394. }
  395. static inline void DICTIONARY_STATS_DICT_DESTROY_QUEUED_MINUS1(DICTIONARY *dict) {
  396. __atomic_fetch_sub(&dict->stats->dictionaries.deleted, 1, __ATOMIC_RELAXED);
  397. }
  398. static inline void DICTIONARY_STATS_DICT_FLUSHES_PLUS1(DICTIONARY *dict) {
  399. __atomic_fetch_add(&dict->stats->ops.flushes, 1, __ATOMIC_RELAXED);
  400. }
  401. #else
  402. #define DICTIONARY_STATS_TRAVERSALS_PLUS1(dict) do {;} while(0)
  403. #define DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict) do {;} while(0)
  404. #define DICTIONARY_STATS_CHECK_SPINS_PLUS(dict, count) do {;} while(0)
  405. #define DICTIONARY_STATS_INSERT_SPINS_PLUS(dict, count) do {;} while(0)
  406. #define DICTIONARY_STATS_DELETE_SPINS_PLUS(dict, count) do {;} while(0)
  407. #define DICTIONARY_STATS_SEARCH_IGNORES_PLUS1(dict) do {;} while(0)
  408. #define DICTIONARY_STATS_CALLBACK_INSERTS_PLUS1(dict) do {;} while(0)
  409. #define DICTIONARY_STATS_CALLBACK_CONFLICTS_PLUS1(dict) do {;} while(0)
  410. #define DICTIONARY_STATS_CALLBACK_REACTS_PLUS1(dict) do {;} while(0)
  411. #define DICTIONARY_STATS_CALLBACK_DELETES_PLUS1(dict) do {;} while(0)
  412. #define DICTIONARY_STATS_GARBAGE_COLLECTIONS_PLUS1(dict) do {;} while(0)
  413. #define DICTIONARY_STATS_DICT_CREATIONS_PLUS1(dict) do {;} while(0)
  414. #define DICTIONARY_STATS_DICT_DESTRUCTIONS_PLUS1(dict) do {;} while(0)
  415. #define DICTIONARY_STATS_DICT_DESTROY_QUEUED_PLUS1(dict) do {;} while(0)
  416. #define DICTIONARY_STATS_DICT_DESTROY_QUEUED_MINUS1(dict) do {;} while(0)
  417. #define DICTIONARY_STATS_DICT_FLUSHES_PLUS1(dict) do {;} while(0)
  418. #endif
  419. static inline void DICTIONARY_REFERENCED_ITEMS_PLUS1(DICTIONARY *dict) {
  420. #ifdef DICT_WITH_STATS
  421. __atomic_fetch_add(&dict->stats->items.referenced, 1, __ATOMIC_RELAXED);
  422. #endif
  423. if(unlikely(is_dictionary_single_threaded(dict)))
  424. ++dict->referenced_items;
  425. else
  426. __atomic_add_fetch(&dict->referenced_items, 1, __ATOMIC_RELAXED);
  427. }
  428. static inline void DICTIONARY_REFERENCED_ITEMS_MINUS1(DICTIONARY *dict) {
  429. #ifdef DICT_WITH_STATS
  430. __atomic_fetch_sub(&dict->stats->items.referenced, 1, __ATOMIC_RELAXED);
  431. #endif
  432. long int referenced_items; (void)referenced_items;
  433. if(unlikely(is_dictionary_single_threaded(dict)))
  434. referenced_items = --dict->referenced_items;
  435. else
  436. referenced_items = __atomic_sub_fetch(&dict->referenced_items, 1, __ATOMIC_SEQ_CST);
  437. internal_fatal(referenced_items < 0,
  438. "DICT: negative number of referenced items (%ld) in dictionary created from %s() (%zu@%s)",
  439. referenced_items,
  440. dict->creation_function,
  441. dict->creation_line,
  442. dict->creation_file);
  443. }
  444. static inline void DICTIONARY_PENDING_DELETES_PLUS1(DICTIONARY *dict) {
  445. #ifdef DICT_WITH_STATS
  446. __atomic_fetch_add(&dict->stats->items.pending_deletion, 1, __ATOMIC_RELAXED);
  447. #endif
  448. if(unlikely(is_dictionary_single_threaded(dict)))
  449. ++dict->pending_deletion_items;
  450. else
  451. __atomic_add_fetch(&dict->pending_deletion_items, 1, __ATOMIC_RELEASE);
  452. }
  453. static inline long int DICTIONARY_PENDING_DELETES_MINUS1(DICTIONARY *dict) {
  454. #ifdef DICT_WITH_STATS
  455. __atomic_fetch_sub(&dict->stats->items.pending_deletion, 1, __ATOMIC_RELEASE);
  456. #endif
  457. if(unlikely(is_dictionary_single_threaded(dict)))
  458. return --dict->pending_deletion_items;
  459. else
  460. return __atomic_sub_fetch(&dict->pending_deletion_items, 1, __ATOMIC_ACQUIRE);
  461. }
  462. static inline long int DICTIONARY_PENDING_DELETES_GET(DICTIONARY *dict) {
  463. if(unlikely(is_dictionary_single_threaded(dict)))
  464. return dict->pending_deletion_items;
  465. else
  466. return __atomic_load_n(&dict->pending_deletion_items, __ATOMIC_SEQ_CST);
  467. }
  468. static inline REFCOUNT DICTIONARY_ITEM_REFCOUNT_GET(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  469. if(unlikely(dict && is_dictionary_single_threaded(dict))) // this is an exception, dict can be null
  470. return item->refcount;
  471. else
  472. return (REFCOUNT)__atomic_load_n(&item->refcount, __ATOMIC_ACQUIRE);
  473. }
  474. static inline REFCOUNT DICTIONARY_ITEM_REFCOUNT_GET_SOLE(DICTIONARY_ITEM *item) {
  475. return (REFCOUNT)__atomic_load_n(&item->refcount, __ATOMIC_ACQUIRE);
  476. }
  477. // ----------------------------------------------------------------------------
  478. // callbacks execution
  479. static void dictionary_execute_insert_callback(DICTIONARY *dict, DICTIONARY_ITEM *item, void *constructor_data) {
  480. if(likely(!dict->hooks || !dict->hooks->ins_callback))
  481. return;
  482. if(unlikely(is_view_dictionary(dict)))
  483. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  484. internal_error(false,
  485. "DICTIONARY: Running insert callback on item '%s' of dictionary created from %s() %zu@%s.",
  486. item_get_name(item),
  487. dict->creation_function,
  488. dict->creation_line,
  489. dict->creation_file);
  490. dict->hooks->ins_callback(item, item->shared->value, constructor_data?constructor_data:dict->hooks->ins_callback_data);
  491. DICTIONARY_STATS_CALLBACK_INSERTS_PLUS1(dict);
  492. }
  493. static bool dictionary_execute_conflict_callback(DICTIONARY *dict, DICTIONARY_ITEM *item, void *new_value, void *constructor_data) {
  494. if(likely(!dict->hooks || !dict->hooks->conflict_callback))
  495. return false;
  496. if(unlikely(is_view_dictionary(dict)))
  497. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  498. internal_error(false,
  499. "DICTIONARY: Running conflict callback on item '%s' of dictionary created from %s() %zu@%s.",
  500. item_get_name(item),
  501. dict->creation_function,
  502. dict->creation_line,
  503. dict->creation_file);
  504. bool ret = dict->hooks->conflict_callback(
  505. item, item->shared->value, new_value,
  506. constructor_data ? constructor_data : dict->hooks->conflict_callback_data);
  507. DICTIONARY_STATS_CALLBACK_CONFLICTS_PLUS1(dict);
  508. return ret;
  509. }
  510. static void dictionary_execute_react_callback(DICTIONARY *dict, DICTIONARY_ITEM *item, void *constructor_data) {
  511. if(likely(!dict->hooks || !dict->hooks->react_callback))
  512. return;
  513. if(unlikely(is_view_dictionary(dict)))
  514. fatal("DICTIONARY: called %s() on a view.", __FUNCTION__ );
  515. internal_error(false,
  516. "DICTIONARY: Running react callback on item '%s' of dictionary created from %s() %zu@%s.",
  517. item_get_name(item),
  518. dict->creation_function,
  519. dict->creation_line,
  520. dict->creation_file);
  521. dict->hooks->react_callback(item, item->shared->value,
  522. constructor_data?constructor_data:dict->hooks->react_callback_data);
  523. DICTIONARY_STATS_CALLBACK_REACTS_PLUS1(dict);
  524. }
  525. static void dictionary_execute_delete_callback(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  526. if(likely(!dict->hooks || !dict->hooks->del_callback))
  527. return;
  528. // We may execute delete callback on items deleted from a view,
  529. // because we may have references to it, after the master is gone
  530. // so, the shared structure will remain until the last reference is released.
  531. internal_error(false,
  532. "DICTIONARY: Running delete callback on item '%s' of dictionary created from %s() %zu@%s.",
  533. item_get_name(item),
  534. dict->creation_function,
  535. dict->creation_line,
  536. dict->creation_file);
  537. dict->hooks->del_callback(item, item->shared->value, dict->hooks->del_callback_data);
  538. DICTIONARY_STATS_CALLBACK_DELETES_PLUS1(dict);
  539. }
  540. // ----------------------------------------------------------------------------
  541. // dictionary locks
  542. static inline size_t dictionary_locks_init(DICTIONARY *dict) {
  543. if(likely(!is_dictionary_single_threaded(dict))) {
  544. rw_spinlock_init(&dict->index.rw_spinlock);
  545. rw_spinlock_init(&dict->items.rw_spinlock);
  546. }
  547. return 0;
  548. }
  549. static inline size_t dictionary_locks_destroy(DICTIONARY *dict __maybe_unused) {
  550. return 0;
  551. }
  552. static inline void ll_recursive_lock_set_thread_as_writer(DICTIONARY *dict) {
  553. pid_t expected = 0, desired = gettid();
  554. if(!__atomic_compare_exchange_n(&dict->items.writer_pid, &expected, desired, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED))
  555. fatal("DICTIONARY: Cannot set thread %d as exclusive writer, expected %d, desired %d, found %d.", gettid(), expected, desired, __atomic_load_n(&dict->items.writer_pid, __ATOMIC_RELAXED));
  556. }
  557. static inline void ll_recursive_unlock_unset_thread_writer(DICTIONARY *dict) {
  558. pid_t expected = gettid(), desired = 0;
  559. if(!__atomic_compare_exchange_n(&dict->items.writer_pid, &expected, desired, false, __ATOMIC_RELAXED, __ATOMIC_RELAXED))
  560. fatal("DICTIONARY: Cannot unset thread %d as exclusive writer, expected %d, desired %d, found %d.", gettid(), expected, desired, __atomic_load_n(&dict->items.writer_pid, __ATOMIC_RELAXED));
  561. }
  562. static inline bool ll_recursive_lock_is_thread_the_writer(DICTIONARY *dict) {
  563. pid_t tid = gettid();
  564. return tid > 0 && tid == __atomic_load_n(&dict->items.writer_pid, __ATOMIC_RELAXED);
  565. }
  566. static inline void ll_recursive_lock(DICTIONARY *dict, char rw) {
  567. if(unlikely(is_dictionary_single_threaded(dict)))
  568. return;
  569. if(ll_recursive_lock_is_thread_the_writer(dict)) {
  570. dict->items.writer_depth++;
  571. return;
  572. }
  573. if(rw == DICTIONARY_LOCK_READ || rw == DICTIONARY_LOCK_REENTRANT || rw == 'R') {
  574. // read lock
  575. rw_spinlock_read_lock(&dict->items.rw_spinlock);
  576. }
  577. else {
  578. // write lock
  579. rw_spinlock_write_lock(&dict->items.rw_spinlock);
  580. ll_recursive_lock_set_thread_as_writer(dict);
  581. }
  582. }
  583. static inline void ll_recursive_unlock(DICTIONARY *dict, char rw) {
  584. if(unlikely(is_dictionary_single_threaded(dict)))
  585. return;
  586. if(ll_recursive_lock_is_thread_the_writer(dict) && dict->items.writer_depth > 0) {
  587. dict->items.writer_depth--;
  588. return;
  589. }
  590. if(rw == DICTIONARY_LOCK_READ || rw == DICTIONARY_LOCK_REENTRANT || rw == 'R') {
  591. // read unlock
  592. rw_spinlock_read_unlock(&dict->items.rw_spinlock);
  593. }
  594. else {
  595. // write unlock
  596. ll_recursive_unlock_unset_thread_writer(dict);
  597. rw_spinlock_write_unlock(&dict->items.rw_spinlock);
  598. }
  599. }
  600. inline void dictionary_write_lock(DICTIONARY *dict) {
  601. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  602. }
  603. inline void dictionary_write_unlock(DICTIONARY *dict) {
  604. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  605. }
  606. static inline void dictionary_index_lock_rdlock(DICTIONARY *dict) {
  607. if(unlikely(is_dictionary_single_threaded(dict)))
  608. return;
  609. rw_spinlock_read_lock(&dict->index.rw_spinlock);
  610. }
  611. static inline void dictionary_index_rdlock_unlock(DICTIONARY *dict) {
  612. if(unlikely(is_dictionary_single_threaded(dict)))
  613. return;
  614. rw_spinlock_read_unlock(&dict->index.rw_spinlock);
  615. }
  616. static inline void dictionary_index_lock_wrlock(DICTIONARY *dict) {
  617. if(unlikely(is_dictionary_single_threaded(dict)))
  618. return;
  619. rw_spinlock_write_lock(&dict->index.rw_spinlock);
  620. }
  621. static inline void dictionary_index_wrlock_unlock(DICTIONARY *dict) {
  622. if(unlikely(is_dictionary_single_threaded(dict)))
  623. return;
  624. rw_spinlock_write_unlock(&dict->index.rw_spinlock);
  625. }
  626. // ----------------------------------------------------------------------------
  627. // items garbage collector
  628. static void garbage_collect_pending_deletes(DICTIONARY *dict) {
  629. usec_t last_master_deletion_us = dict->hooks?__atomic_load_n(&dict->hooks->last_master_deletion_us, __ATOMIC_RELAXED):0;
  630. usec_t last_gc_run_us = __atomic_load_n(&dict->last_gc_run_us, __ATOMIC_RELAXED);
  631. bool is_view = is_view_dictionary(dict);
  632. if(likely(!(
  633. DICTIONARY_PENDING_DELETES_GET(dict) > 0 ||
  634. (is_view && last_master_deletion_us > last_gc_run_us)
  635. )))
  636. return;
  637. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  638. __atomic_store_n(&dict->last_gc_run_us, now_realtime_usec(), __ATOMIC_RELAXED);
  639. if(is_view)
  640. dictionary_index_lock_wrlock(dict);
  641. DICTIONARY_STATS_GARBAGE_COLLECTIONS_PLUS1(dict);
  642. size_t deleted = 0, pending = 0, examined = 0;
  643. DICTIONARY_ITEM *item = dict->items.list, *item_next;
  644. while(item) {
  645. examined++;
  646. // this will clean up
  647. item_next = item->next;
  648. int rc = item_check_and_acquire_advanced(dict, item, is_view);
  649. if(rc == RC_ITEM_MARKED_FOR_DELETION) {
  650. // we didn't get a reference
  651. if(item_is_not_referenced_and_can_be_removed(dict, item)) {
  652. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(dict->items.list, item, prev, next);
  653. dict_item_free_with_hooks(dict, item);
  654. deleted++;
  655. pending = DICTIONARY_PENDING_DELETES_MINUS1(dict);
  656. if (!pending)
  657. break;
  658. }
  659. }
  660. else if(rc == RC_ITEM_IS_CURRENTLY_BEING_DELETED)
  661. ; // do not touch this item (we didn't get a reference)
  662. else if(rc == RC_ITEM_OK)
  663. item_release(dict, item);
  664. item = item_next;
  665. }
  666. if(is_view)
  667. dictionary_index_wrlock_unlock(dict);
  668. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  669. (void)deleted;
  670. (void)examined;
  671. internal_error(false, "DICTIONARY: garbage collected dictionary created by %s (%zu@%s), "
  672. "examined %zu items, deleted %zu items, still pending %zu items",
  673. dict->creation_function, dict->creation_line, dict->creation_file,
  674. examined, deleted, pending);
  675. }
  676. void dictionary_garbage_collect(DICTIONARY *dict) {
  677. if(!dict) return;
  678. garbage_collect_pending_deletes(dict);
  679. }
  680. // ----------------------------------------------------------------------------
  681. // reference counters
  682. static inline size_t reference_counter_init(DICTIONARY *dict __maybe_unused) {
  683. // allocate memory required for reference counters
  684. // return number of bytes
  685. return 0;
  686. }
  687. static inline size_t reference_counter_free(DICTIONARY *dict __maybe_unused) {
  688. // free memory required for reference counters
  689. // return number of bytes
  690. return 0;
  691. }
  692. static void item_acquire(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  693. REFCOUNT refcount;
  694. if(unlikely(is_dictionary_single_threaded(dict)))
  695. refcount = ++item->refcount;
  696. else
  697. // increment the refcount
  698. refcount = __atomic_add_fetch(&item->refcount, 1, __ATOMIC_SEQ_CST);
  699. if(refcount <= 0) {
  700. internal_error(
  701. true,
  702. "DICTIONARY: attempted to acquire item which is deleted (refcount = %d): "
  703. "'%s' on dictionary created by %s() (%zu@%s)",
  704. refcount - 1,
  705. item_get_name(item),
  706. dict->creation_function,
  707. dict->creation_line,
  708. dict->creation_file);
  709. fatal(
  710. "DICTIONARY: request to acquire item '%s', which is deleted (refcount = %d)!",
  711. item_get_name(item),
  712. refcount - 1);
  713. }
  714. if(refcount == 1) {
  715. // referenced items counts number of unique items referenced
  716. // so, we increase it only when refcount == 1
  717. DICTIONARY_REFERENCED_ITEMS_PLUS1(dict);
  718. // if this is a deleted item, but the counter increased to 1
  719. // we need to remove it from the pending items to delete
  720. if(item_flag_check(item, ITEM_FLAG_DELETED))
  721. DICTIONARY_PENDING_DELETES_MINUS1(dict);
  722. }
  723. }
  724. static void item_release(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  725. // this function may be called without any lock on the dictionary
  726. // or even when someone else has 'write' lock on the dictionary
  727. bool is_deleted;
  728. REFCOUNT refcount;
  729. if(unlikely(is_dictionary_single_threaded(dict))) {
  730. is_deleted = item->flags & ITEM_FLAG_DELETED;
  731. refcount = --item->refcount;
  732. }
  733. else {
  734. // get the flags before decrementing any reference counters
  735. // (the other way around may lead to use-after-free)
  736. is_deleted = item_flag_check(item, ITEM_FLAG_DELETED);
  737. // decrement the refcount
  738. refcount = __atomic_sub_fetch(&item->refcount, 1, __ATOMIC_RELEASE);
  739. }
  740. if(refcount < 0) {
  741. internal_error(
  742. true,
  743. "DICTIONARY: attempted to release item without references (refcount = %d): "
  744. "'%s' on dictionary created by %s() (%zu@%s)",
  745. refcount + 1,
  746. item_get_name(item),
  747. dict->creation_function,
  748. dict->creation_line,
  749. dict->creation_file);
  750. fatal(
  751. "DICTIONARY: attempted to release item '%s' without references (refcount = %d)",
  752. item_get_name(item),
  753. refcount + 1);
  754. }
  755. if(refcount == 0) {
  756. if(is_deleted)
  757. DICTIONARY_PENDING_DELETES_PLUS1(dict);
  758. // referenced items counts number of unique items referenced
  759. // so, we decrease it only when refcount == 0
  760. DICTIONARY_REFERENCED_ITEMS_MINUS1(dict);
  761. }
  762. }
  763. static int item_check_and_acquire_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item, bool having_index_lock) {
  764. size_t spins = 0;
  765. REFCOUNT refcount, desired;
  766. int ret = RC_ITEM_OK;
  767. refcount = DICTIONARY_ITEM_REFCOUNT_GET(dict, item);
  768. do {
  769. spins++;
  770. if(refcount < 0) {
  771. // we can't use this item
  772. ret = RC_ITEM_IS_CURRENTLY_BEING_DELETED;
  773. break;
  774. }
  775. if(item_flag_check(item, ITEM_FLAG_DELETED)) {
  776. // we can't use this item
  777. ret = RC_ITEM_MARKED_FOR_DELETION;
  778. break;
  779. }
  780. desired = refcount + 1;
  781. } while(!__atomic_compare_exchange_n(&item->refcount, &refcount, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
  782. // if ret == ITEM_OK, we acquired the item
  783. if(ret == RC_ITEM_OK) {
  784. if (unlikely(is_view_dictionary(dict) &&
  785. item_shared_flag_check(item, ITEM_FLAG_DELETED) &&
  786. !item_flag_check(item, ITEM_FLAG_DELETED))) {
  787. // but, we can't use this item
  788. if (having_index_lock) {
  789. // delete it from the hashtable
  790. if(hashtable_delete_unsafe(dict, item_get_name(item), item->key_len, item) == 0)
  791. netdata_log_error("DICTIONARY: INTERNAL ERROR VIEW: tried to delete item with name '%s', name_len %u that is not in the index", item_get_name(item), (KEY_LEN_TYPE)(item->key_len - 1));
  792. else
  793. pointer_del(dict, item);
  794. // mark it in our dictionary as deleted too,
  795. // this is safe to be done here, because we have got
  796. // a reference counter on item
  797. dict_item_set_deleted(dict, item);
  798. // decrement the refcount we incremented above
  799. if (__atomic_sub_fetch(&item->refcount, 1, __ATOMIC_RELEASE) == 0) {
  800. // this is a deleted item, and we are the last one
  801. DICTIONARY_PENDING_DELETES_PLUS1(dict);
  802. }
  803. // do not touch the item below this point
  804. } else {
  805. // this is traversal / walkthrough
  806. // decrement the refcount we incremented above
  807. __atomic_sub_fetch(&item->refcount, 1, __ATOMIC_RELEASE);
  808. }
  809. return RC_ITEM_MARKED_FOR_DELETION;
  810. }
  811. if(desired == 1)
  812. DICTIONARY_REFERENCED_ITEMS_PLUS1(dict);
  813. }
  814. if(unlikely(spins > 1))
  815. DICTIONARY_STATS_CHECK_SPINS_PLUS(dict, spins - 1);
  816. return ret;
  817. }
  818. // if a dictionary item can be deleted, return true, otherwise return false
  819. // we use the private reference counter
  820. static inline int item_is_not_referenced_and_can_be_removed_advanced(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  821. // if we can set refcount to REFCOUNT_DELETING, we can delete this item
  822. size_t spins = 0;
  823. REFCOUNT refcount, desired = REFCOUNT_DELETING;
  824. int ret = RC_ITEM_OK;
  825. refcount = DICTIONARY_ITEM_REFCOUNT_GET(dict, item);
  826. do {
  827. spins++;
  828. if(refcount < 0) {
  829. // we can't use this item
  830. ret = RC_ITEM_IS_CURRENTLY_BEING_DELETED;
  831. break;
  832. }
  833. if(refcount > 0) {
  834. // we can't delete this
  835. ret = RC_ITEM_IS_REFERENCED;
  836. break;
  837. }
  838. if(item_flag_check(item, ITEM_FLAG_BEING_CREATED)) {
  839. // we can't use this item
  840. ret = RC_ITEM_IS_CURRENTLY_BEING_CREATED;
  841. break;
  842. }
  843. } while(!__atomic_compare_exchange_n(&item->refcount, &refcount, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
  844. #ifdef NETDATA_INTERNAL_CHECKS
  845. if(ret == RC_ITEM_OK)
  846. item->deleter_pid = gettid();
  847. #endif
  848. if(unlikely(spins > 1))
  849. DICTIONARY_STATS_DELETE_SPINS_PLUS(dict, spins - 1);
  850. return ret;
  851. }
  852. // if a dictionary item can be freed, return true, otherwise return false
  853. // we use the shared reference counter
  854. static inline bool item_shared_release_and_check_if_it_can_be_freed(DICTIONARY *dict __maybe_unused, DICTIONARY_ITEM *item) {
  855. // if we can set refcount to REFCOUNT_DELETING, we can delete this item
  856. REFCOUNT links = __atomic_sub_fetch(&item->shared->links, 1, __ATOMIC_RELEASE);
  857. if(links == 0 && __atomic_compare_exchange_n(&item->shared->links, &links, REFCOUNT_DELETING, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED)) {
  858. // we can delete it
  859. return true;
  860. }
  861. // we can't delete it
  862. return false;
  863. }
  864. // ----------------------------------------------------------------------------
  865. // hash table operations
  866. static size_t hashtable_init_unsafe(DICTIONARY *dict) {
  867. dict->index.JudyHSArray = NULL;
  868. return 0;
  869. }
  870. static size_t hashtable_destroy_unsafe(DICTIONARY *dict) {
  871. if(unlikely(!dict->index.JudyHSArray)) return 0;
  872. pointer_destroy_index(dict);
  873. JError_t J_Error;
  874. Word_t ret = JudyHSFreeArray(&dict->index.JudyHSArray, &J_Error);
  875. if(unlikely(ret == (Word_t) JERR)) {
  876. netdata_log_error("DICTIONARY: Cannot destroy JudyHS, JU_ERRNO_* == %u, ID == %d",
  877. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  878. }
  879. netdata_log_debug(D_DICTIONARY, "Dictionary: hash table freed %lu bytes", ret);
  880. dict->index.JudyHSArray = NULL;
  881. return (size_t)ret;
  882. }
  883. static inline void **hashtable_insert_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  884. JError_t J_Error;
  885. Pvoid_t *Rc = JudyHSIns(&dict->index.JudyHSArray, (void *)name, name_len, &J_Error);
  886. if (unlikely(Rc == PJERR)) {
  887. netdata_log_error("DICTIONARY: Cannot insert entry with name '%s' to JudyHS, JU_ERRNO_* == %u, ID == %d",
  888. name, JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  889. }
  890. // if *Rc == 0, new item added to the array
  891. // otherwise the existing item value is returned in *Rc
  892. // we return a pointer to a pointer, so that the caller can
  893. // put anything needed at the value of the index.
  894. // The pointer to pointer we return has to be used before
  895. // any other operation that may change the index (insert/delete).
  896. return Rc;
  897. }
  898. static inline int hashtable_delete_unsafe(DICTIONARY *dict, const char *name, size_t name_len, void *item) {
  899. (void)item;
  900. if(unlikely(!dict->index.JudyHSArray)) return 0;
  901. JError_t J_Error;
  902. int ret = JudyHSDel(&dict->index.JudyHSArray, (void *)name, name_len, &J_Error);
  903. if(unlikely(ret == JERR)) {
  904. netdata_log_error("DICTIONARY: Cannot delete entry with name '%s' from JudyHS, JU_ERRNO_* == %u, ID == %d",
  905. name,
  906. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  907. return 0;
  908. }
  909. // Hey, this is problematic! We need the value back, not just an int with a status!
  910. // https://sourceforge.net/p/judy/feature-requests/23/
  911. if(unlikely(ret == 0)) {
  912. // not found in the dictionary
  913. return 0;
  914. }
  915. else {
  916. // found and deleted from the dictionary
  917. return 1;
  918. }
  919. }
  920. static inline DICTIONARY_ITEM *hashtable_get_unsafe(DICTIONARY *dict, const char *name, size_t name_len) {
  921. if(unlikely(!dict->index.JudyHSArray)) return NULL;
  922. DICTIONARY_STATS_SEARCHES_PLUS1(dict);
  923. Pvoid_t *Rc;
  924. Rc = JudyHSGet(dict->index.JudyHSArray, (void *)name, name_len);
  925. if(likely(Rc)) {
  926. // found in the hash table
  927. pointer_check(dict, (DICTIONARY_ITEM *)*Rc);
  928. return (DICTIONARY_ITEM *)*Rc;
  929. }
  930. else {
  931. // not found in the hash table
  932. return NULL;
  933. }
  934. }
  935. static inline void hashtable_inserted_item_unsafe(DICTIONARY *dict, void *item) {
  936. (void)dict;
  937. (void)item;
  938. // this is called just after an item is successfully inserted to the hashtable
  939. // we don't need this for judy, but we may need it if we integrate more hash tables
  940. ;
  941. }
  942. // ----------------------------------------------------------------------------
  943. // linked list management
  944. static inline void item_linked_list_add(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  945. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  946. if(dict->options & DICT_OPTION_ADD_IN_FRONT)
  947. DOUBLE_LINKED_LIST_PREPEND_ITEM_UNSAFE(dict->items.list, item, prev, next);
  948. else
  949. DOUBLE_LINKED_LIST_APPEND_ITEM_UNSAFE(dict->items.list, item, prev, next);
  950. #ifdef NETDATA_INTERNAL_CHECKS
  951. item->ll_adder_pid = gettid();
  952. #endif
  953. // clear the BEING created flag,
  954. // after it has been inserted into the linked list
  955. item_flag_clear(item, ITEM_FLAG_BEING_CREATED);
  956. garbage_collect_pending_deletes(dict);
  957. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  958. }
  959. static inline void item_linked_list_remove(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  960. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  961. DOUBLE_LINKED_LIST_REMOVE_ITEM_UNSAFE(dict->items.list, item, prev, next);
  962. #ifdef NETDATA_INTERNAL_CHECKS
  963. item->ll_remover_pid = gettid();
  964. #endif
  965. garbage_collect_pending_deletes(dict);
  966. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  967. }
  968. // ----------------------------------------------------------------------------
  969. // ITEM initialization and updates
  970. static inline size_t item_set_name(DICTIONARY *dict, DICTIONARY_ITEM *item, const char *name, size_t name_len) {
  971. if(likely(dict->options & DICT_OPTION_NAME_LINK_DONT_CLONE)) {
  972. item->caller_name = (char *)name;
  973. item->key_len = name_len;
  974. }
  975. else {
  976. item->string_name = string_strdupz(name);
  977. item->key_len = string_strlen(item->string_name) + 1;
  978. item->options |= ITEM_OPTION_ALLOCATED_NAME;
  979. }
  980. return item->key_len;
  981. }
  982. static inline size_t item_free_name(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  983. if(likely(!(dict->options & DICT_OPTION_NAME_LINK_DONT_CLONE)))
  984. string_freez(item->string_name);
  985. return item->key_len;
  986. }
  987. static inline const char *item_get_name(const DICTIONARY_ITEM *item) {
  988. if(item->options & ITEM_OPTION_ALLOCATED_NAME)
  989. return string2str(item->string_name);
  990. else
  991. return item->caller_name;
  992. }
  993. static inline size_t item_get_name_len(const DICTIONARY_ITEM *item) {
  994. if(item->options & ITEM_OPTION_ALLOCATED_NAME)
  995. return string_strlen(item->string_name);
  996. else
  997. return strlen(item->caller_name);
  998. }
  999. static ARAL *dict_items_aral = NULL;
  1000. static ARAL *dict_shared_items_aral = NULL;
  1001. void dictionary_static_items_aral_init(void) {
  1002. static SPINLOCK spinlock;
  1003. if(unlikely(!dict_items_aral || !dict_shared_items_aral)) {
  1004. spinlock_lock(&spinlock);
  1005. // we have to check again
  1006. if(!dict_items_aral)
  1007. dict_items_aral = aral_create(
  1008. "dict-items",
  1009. sizeof(DICTIONARY_ITEM),
  1010. 0,
  1011. 65536,
  1012. aral_by_size_statistics(),
  1013. NULL, NULL, false, false);
  1014. // we have to check again
  1015. if(!dict_shared_items_aral)
  1016. dict_shared_items_aral = aral_create(
  1017. "dict-shared-items",
  1018. sizeof(DICTIONARY_ITEM_SHARED),
  1019. 0,
  1020. 65536,
  1021. aral_by_size_statistics(),
  1022. NULL, NULL, false, false);
  1023. spinlock_unlock(&spinlock);
  1024. }
  1025. }
  1026. static DICTIONARY_ITEM *dict_item_create(DICTIONARY *dict __maybe_unused, size_t *allocated_bytes, DICTIONARY_ITEM *master_item) {
  1027. DICTIONARY_ITEM *item;
  1028. size_t size = sizeof(DICTIONARY_ITEM);
  1029. item = aral_mallocz(dict_items_aral);
  1030. memset(item, 0, sizeof(DICTIONARY_ITEM));
  1031. #ifdef NETDATA_INTERNAL_CHECKS
  1032. item->creator_pid = gettid();
  1033. #endif
  1034. item->refcount = 1;
  1035. item->flags = ITEM_FLAG_BEING_CREATED;
  1036. *allocated_bytes += size;
  1037. if(master_item) {
  1038. item->shared = master_item->shared;
  1039. if(unlikely(__atomic_add_fetch(&item->shared->links, 1, __ATOMIC_ACQUIRE) <= 1))
  1040. fatal("DICTIONARY: attempted to link to a shared item structure that had zero references");
  1041. }
  1042. else {
  1043. size = sizeof(DICTIONARY_ITEM_SHARED);
  1044. item->shared = aral_mallocz(dict_shared_items_aral);
  1045. memset(item->shared, 0, sizeof(DICTIONARY_ITEM_SHARED));
  1046. item->shared->links = 1;
  1047. *allocated_bytes += size;
  1048. }
  1049. #ifdef NETDATA_INTERNAL_CHECKS
  1050. item->dict = dict;
  1051. #endif
  1052. return item;
  1053. }
  1054. static inline void *dict_item_value_mallocz(DICTIONARY *dict, size_t value_len) {
  1055. if(dict->value_aral) {
  1056. internal_fatal(aral_element_size(dict->value_aral) != value_len,
  1057. "DICTIONARY: item value size %zu does not match the configured fixed one %zu",
  1058. value_len, aral_element_size(dict->value_aral));
  1059. return aral_mallocz(dict->value_aral);
  1060. }
  1061. else
  1062. return mallocz(value_len);
  1063. }
  1064. static inline void dict_item_value_freez(DICTIONARY *dict, void *ptr) {
  1065. if(dict->value_aral)
  1066. aral_freez(dict->value_aral, ptr);
  1067. else
  1068. freez(ptr);
  1069. }
  1070. static void *dict_item_value_create(DICTIONARY *dict, void *value, size_t value_len) {
  1071. void *ptr = NULL;
  1072. if(likely(value_len)) {
  1073. if (likely(value)) {
  1074. // a value has been supplied
  1075. // copy it
  1076. ptr = dict_item_value_mallocz(dict, value_len);
  1077. memcpy(ptr, value, value_len);
  1078. }
  1079. else {
  1080. // no value has been supplied
  1081. // allocate a clear memory block
  1082. ptr = dict_item_value_mallocz(dict, value_len);
  1083. memset(ptr, 0, value_len);
  1084. }
  1085. }
  1086. // else
  1087. // the caller wants an item without any value
  1088. return ptr;
  1089. }
  1090. static DICTIONARY_ITEM *dict_item_create_with_hooks(DICTIONARY *dict, const char *name, size_t name_len, void *value, size_t value_len, void *constructor_data, DICTIONARY_ITEM *master_item) {
  1091. #ifdef NETDATA_INTERNAL_CHECKS
  1092. if(unlikely(name_len > KEY_LEN_MAX))
  1093. fatal("DICTIONARY: tried to index a key of size %zu, but the maximum acceptable is %zu", name_len, (size_t)KEY_LEN_MAX);
  1094. if(unlikely(value_len > VALUE_LEN_MAX))
  1095. fatal("DICTIONARY: tried to add an item of size %zu, but the maximum acceptable is %zu", value_len, (size_t)VALUE_LEN_MAX);
  1096. #endif
  1097. size_t item_size = 0, key_size = 0, value_size = 0;
  1098. DICTIONARY_ITEM *item = dict_item_create(dict, &item_size, master_item);
  1099. key_size += item_set_name(dict, item, name, name_len);
  1100. if(unlikely(is_view_dictionary(dict))) {
  1101. // we are on a view dictionary
  1102. // do not touch the value
  1103. ;
  1104. #ifdef NETDATA_INTERNAL_CHECKS
  1105. if(unlikely(!master_item))
  1106. fatal("DICTIONARY: cannot add an item to a view without a master item.");
  1107. #endif
  1108. }
  1109. else {
  1110. // we are on the master dictionary
  1111. if(unlikely(dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE))
  1112. item->shared->value = value;
  1113. else
  1114. item->shared->value = dict_item_value_create(dict, value, value_len);
  1115. item->shared->value_len = value_len;
  1116. value_size += value_len;
  1117. dictionary_execute_insert_callback(dict, item, constructor_data);
  1118. }
  1119. DICTIONARY_ENTRIES_PLUS1(dict);
  1120. DICTIONARY_STATS_PLUS_MEMORY(dict, key_size, item_size, value_size);
  1121. return item;
  1122. }
  1123. static void dict_item_reset_value_with_hooks(DICTIONARY *dict, DICTIONARY_ITEM *item, void *value, size_t value_len, void *constructor_data) {
  1124. if(unlikely(is_view_dictionary(dict)))
  1125. fatal("DICTIONARY: %s() should never be called on views.", __FUNCTION__ );
  1126. netdata_log_debug(D_DICTIONARY, "Dictionary entry with name '%s' found. Changing its value.", item_get_name(item));
  1127. DICTIONARY_VALUE_RESETS_PLUS1(dict);
  1128. if(item->shared->value_len != value_len) {
  1129. DICTIONARY_STATS_PLUS_MEMORY(dict, 0, 0, value_len);
  1130. DICTIONARY_STATS_MINUS_MEMORY(dict, 0, 0, item->shared->value_len);
  1131. }
  1132. dictionary_execute_delete_callback(dict, item);
  1133. if(likely(dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE)) {
  1134. netdata_log_debug(D_DICTIONARY, "Dictionary: linking value to '%s'", item_get_name(item));
  1135. item->shared->value = value;
  1136. item->shared->value_len = value_len;
  1137. }
  1138. else {
  1139. netdata_log_debug(D_DICTIONARY, "Dictionary: cloning value to '%s'", item_get_name(item));
  1140. void *old_value = item->shared->value;
  1141. void *new_value = NULL;
  1142. if(value_len) {
  1143. new_value = dict_item_value_mallocz(dict, value_len);
  1144. if(value) memcpy(new_value, value, value_len);
  1145. else memset(new_value, 0, value_len);
  1146. }
  1147. item->shared->value = new_value;
  1148. item->shared->value_len = value_len;
  1149. netdata_log_debug(D_DICTIONARY, "Dictionary: freeing old value of '%s'", item_get_name(item));
  1150. dict_item_value_freez(dict, old_value);
  1151. }
  1152. dictionary_execute_insert_callback(dict, item, constructor_data);
  1153. }
  1154. static size_t dict_item_free_with_hooks(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1155. netdata_log_debug(D_DICTIONARY, "Destroying name value entry for name '%s'.", item_get_name(item));
  1156. if(!item_flag_check(item, ITEM_FLAG_DELETED))
  1157. DICTIONARY_ENTRIES_MINUS1(dict);
  1158. size_t item_size = 0, key_size = 0, value_size = 0;
  1159. key_size += item->key_len;
  1160. if(unlikely(!(dict->options & DICT_OPTION_NAME_LINK_DONT_CLONE)))
  1161. item_free_name(dict, item);
  1162. if(item_shared_release_and_check_if_it_can_be_freed(dict, item)) {
  1163. dictionary_execute_delete_callback(dict, item);
  1164. if(unlikely(!(dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE))) {
  1165. netdata_log_debug(D_DICTIONARY, "Dictionary freeing value of '%s'", item_get_name(item));
  1166. dict_item_value_freez(dict, item->shared->value);
  1167. item->shared->value = NULL;
  1168. }
  1169. value_size += item->shared->value_len;
  1170. aral_freez(dict_shared_items_aral, item->shared);
  1171. item->shared = NULL;
  1172. item_size += sizeof(DICTIONARY_ITEM_SHARED);
  1173. }
  1174. aral_freez(dict_items_aral, item);
  1175. item_size += sizeof(DICTIONARY_ITEM);
  1176. DICTIONARY_STATS_MINUS_MEMORY(dict, key_size, item_size, value_size);
  1177. // we return the memory we actually freed
  1178. return item_size + ((dict->options & DICT_OPTION_VALUE_LINK_DONT_CLONE) ? 0 : value_size);
  1179. }
  1180. // ----------------------------------------------------------------------------
  1181. // item operations
  1182. static void dict_item_shared_set_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1183. if(is_master_dictionary(dict)) {
  1184. item_shared_flag_set(item, ITEM_FLAG_DELETED);
  1185. if(dict->hooks)
  1186. __atomic_store_n(&dict->hooks->last_master_deletion_us, now_realtime_usec(), __ATOMIC_RELAXED);
  1187. }
  1188. }
  1189. // returns true if we set the deleted flag on this item
  1190. static bool dict_item_set_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1191. ITEM_FLAGS expected, desired;
  1192. expected = __atomic_load_n(&item->flags, __ATOMIC_RELAXED);
  1193. do {
  1194. if (expected & ITEM_FLAG_DELETED)
  1195. return false;
  1196. desired = expected | ITEM_FLAG_DELETED;
  1197. } while(!__atomic_compare_exchange_n(&item->flags, &expected, desired, false, __ATOMIC_ACQUIRE, __ATOMIC_RELAXED));
  1198. DICTIONARY_ENTRIES_MINUS1(dict);
  1199. return true;
  1200. }
  1201. static inline void dict_item_free_or_mark_deleted(DICTIONARY *dict, DICTIONARY_ITEM *item) {
  1202. int rc = item_is_not_referenced_and_can_be_removed_advanced(dict, item);
  1203. switch(rc) {
  1204. case RC_ITEM_OK:
  1205. // the item is ours, refcount set to -100
  1206. dict_item_shared_set_deleted(dict, item);
  1207. item_linked_list_remove(dict, item);
  1208. dict_item_free_with_hooks(dict, item);
  1209. break;
  1210. case RC_ITEM_IS_REFERENCED:
  1211. case RC_ITEM_IS_CURRENTLY_BEING_CREATED:
  1212. // the item is currently referenced by others
  1213. dict_item_shared_set_deleted(dict, item);
  1214. dict_item_set_deleted(dict, item);
  1215. // after this point do not touch the item
  1216. break;
  1217. case RC_ITEM_IS_CURRENTLY_BEING_DELETED:
  1218. // an item that is currently being deleted by someone else - don't touch it
  1219. break;
  1220. default:
  1221. internal_error(true, "Hey dev! You forgot to add the new condition here!");
  1222. break;
  1223. }
  1224. }
  1225. // this is used by traversal functions to remove the current item
  1226. // if it is deleted, and it has zero references. This will eliminate
  1227. // the need for the garbage collector to kick-in later.
  1228. // Most deletions happen during traversal, so this is a nice hack
  1229. // to speed up everything!
  1230. static inline void dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(DICTIONARY *dict, DICTIONARY_ITEM *item, char rw) {
  1231. if(rw == DICTIONARY_LOCK_WRITE) {
  1232. bool should_be_deleted = item_flag_check(item, ITEM_FLAG_DELETED);
  1233. item_release(dict, item);
  1234. if(should_be_deleted && item_is_not_referenced_and_can_be_removed(dict, item)) {
  1235. // this has to be before removing from the linked list,
  1236. // otherwise the garbage collector will also kick in!
  1237. DICTIONARY_PENDING_DELETES_MINUS1(dict);
  1238. item_linked_list_remove(dict, item);
  1239. dict_item_free_with_hooks(dict, item);
  1240. }
  1241. }
  1242. else {
  1243. // we can't do anything under this mode
  1244. item_release(dict, item);
  1245. }
  1246. }
  1247. static bool dict_item_del(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1248. if(name_len == -1)
  1249. name_len = (ssize_t)strlen(name) + 1; // we need the terminating null too
  1250. netdata_log_debug(D_DICTIONARY, "DEL dictionary entry with name '%s'.", name);
  1251. // Unfortunately, the JudyHSDel() does not return the value of the
  1252. // item that was deleted, so we have to find it before we delete it,
  1253. // since we need to release our structures too.
  1254. dictionary_index_lock_wrlock(dict);
  1255. int ret;
  1256. DICTIONARY_ITEM *item = hashtable_get_unsafe(dict, name, name_len);
  1257. if(unlikely(!item)) {
  1258. dictionary_index_wrlock_unlock(dict);
  1259. ret = false;
  1260. }
  1261. else {
  1262. if(hashtable_delete_unsafe(dict, name, name_len, item) == 0)
  1263. netdata_log_error("DICTIONARY: INTERNAL ERROR: tried to delete item with name '%s', name_len %zd that is not in the index",
  1264. name,
  1265. name_len - 1);
  1266. else
  1267. pointer_del(dict, item);
  1268. dictionary_index_wrlock_unlock(dict);
  1269. dict_item_free_or_mark_deleted(dict, item);
  1270. ret = true;
  1271. }
  1272. return ret;
  1273. }
  1274. static DICTIONARY_ITEM *dict_item_add_or_reset_value_and_acquire(DICTIONARY *dict, const char *name, ssize_t name_len, void *value, size_t value_len, void *constructor_data, DICTIONARY_ITEM *master_item) {
  1275. if(unlikely(!name || !*name)) {
  1276. internal_error(
  1277. true,
  1278. "DICTIONARY: attempted to %s() without a name on a dictionary created from %s() %zu@%s.",
  1279. __FUNCTION__,
  1280. dict->creation_function,
  1281. dict->creation_line,
  1282. dict->creation_file);
  1283. return NULL;
  1284. }
  1285. if(unlikely(is_dictionary_destroyed(dict))) {
  1286. internal_error(true, "DICTIONARY: attempted to dictionary_set() on a destroyed dictionary");
  1287. return NULL;
  1288. }
  1289. if(name_len == -1)
  1290. name_len = (ssize_t)strlen(name) + 1; // we need the terminating null too
  1291. netdata_log_debug(D_DICTIONARY, "SET dictionary entry with name '%s'.", name);
  1292. // DISCUSSION:
  1293. // Is it better to gain a read-lock and do a hashtable_get_unsafe()
  1294. // before we write lock to do hashtable_insert_unsafe()?
  1295. //
  1296. // Probably this depends on the use case.
  1297. // For statsd for example that does dictionary_set() to update received values,
  1298. // it could be beneficial to do a get() before we insert().
  1299. //
  1300. // But the caller has the option to do this on his/her own.
  1301. // So, let's do the fastest here and let the caller decide the flow of calls.
  1302. dictionary_index_lock_wrlock(dict);
  1303. bool added_or_updated = false;
  1304. size_t spins = 0;
  1305. DICTIONARY_ITEM *item = NULL;
  1306. do {
  1307. DICTIONARY_ITEM **item_pptr = (DICTIONARY_ITEM **)hashtable_insert_unsafe(dict, name, name_len);
  1308. if (likely(*item_pptr == NULL)) {
  1309. // a new item added to the index
  1310. // create the dictionary item
  1311. item = *item_pptr =
  1312. dict_item_create_with_hooks(dict, name, name_len, value, value_len, constructor_data, master_item);
  1313. pointer_add(dict, item);
  1314. // call the hashtable react
  1315. hashtable_inserted_item_unsafe(dict, item);
  1316. // unlock the index lock, before we add it to the linked list
  1317. // DON'T DO IT THE OTHER WAY AROUND - DO NOT CROSS THE LOCKS!
  1318. dictionary_index_wrlock_unlock(dict);
  1319. item_linked_list_add(dict, item);
  1320. added_or_updated = true;
  1321. }
  1322. else {
  1323. pointer_check(dict, *item_pptr);
  1324. if(item_check_and_acquire_advanced(dict, *item_pptr, true) != RC_ITEM_OK) {
  1325. spins++;
  1326. continue;
  1327. }
  1328. // the item is already in the index
  1329. // so, either we will return the old one
  1330. // or overwrite the value, depending on dictionary flags
  1331. // We should not compare the values here!
  1332. // even if they are the same, we have to do the whole job
  1333. // so that the callbacks will be called.
  1334. item = *item_pptr;
  1335. if(is_view_dictionary(dict)) {
  1336. // view dictionary
  1337. // the item is already there and can be used
  1338. if(item->shared != master_item->shared)
  1339. netdata_log_error("DICTIONARY: changing the master item on a view is not supported. The previous item will remain. To change the key of an item in a view, delete it and add it again.");
  1340. }
  1341. else {
  1342. // master dictionary
  1343. // the user wants to reset its value
  1344. if (!(dict->options & DICT_OPTION_DONT_OVERWRITE_VALUE)) {
  1345. dict_item_reset_value_with_hooks(dict, item, value, value_len, constructor_data);
  1346. added_or_updated = true;
  1347. }
  1348. else if (dictionary_execute_conflict_callback(dict, item, value, constructor_data)) {
  1349. dictionary_version_increment(dict);
  1350. added_or_updated = true;
  1351. }
  1352. else {
  1353. // conflict callback returned false
  1354. // we did really nothing!
  1355. ;
  1356. }
  1357. }
  1358. dictionary_index_wrlock_unlock(dict);
  1359. }
  1360. } while(!item);
  1361. if(unlikely(spins > 0))
  1362. DICTIONARY_STATS_INSERT_SPINS_PLUS(dict, spins);
  1363. if(is_master_dictionary(dict) && added_or_updated)
  1364. dictionary_execute_react_callback(dict, item, constructor_data);
  1365. return item;
  1366. }
  1367. static DICTIONARY_ITEM *dict_item_find_and_acquire(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1368. if(unlikely(!name || !*name)) {
  1369. internal_error(
  1370. true,
  1371. "DICTIONARY: attempted to %s() without a name on a dictionary created from %s() %zu@%s.",
  1372. __FUNCTION__,
  1373. dict->creation_function,
  1374. dict->creation_line,
  1375. dict->creation_file);
  1376. return NULL;
  1377. }
  1378. if(unlikely(is_dictionary_destroyed(dict))) {
  1379. internal_error(true, "DICTIONARY: attempted to dictionary_get() on a destroyed dictionary");
  1380. return NULL;
  1381. }
  1382. if(name_len == -1)
  1383. name_len = (ssize_t)strlen(name) + 1; // we need the terminating null too
  1384. netdata_log_debug(D_DICTIONARY, "GET dictionary entry with name '%s'.", name);
  1385. dictionary_index_lock_rdlock(dict);
  1386. DICTIONARY_ITEM *item = hashtable_get_unsafe(dict, name, name_len);
  1387. if(unlikely(item && !item_check_and_acquire(dict, item))) {
  1388. item = NULL;
  1389. DICTIONARY_STATS_SEARCH_IGNORES_PLUS1(dict);
  1390. }
  1391. dictionary_index_rdlock_unlock(dict);
  1392. return item;
  1393. }
  1394. // ----------------------------------------------------------------------------
  1395. // delayed destruction of dictionaries
  1396. static bool dictionary_free_all_resources(DICTIONARY *dict, size_t *mem, bool force) {
  1397. if(mem)
  1398. *mem = 0;
  1399. if(!force && dictionary_referenced_items(dict))
  1400. return false;
  1401. size_t dict_size = 0, counted_items = 0, item_size = 0, index_size = 0;
  1402. (void)counted_items;
  1403. #ifdef NETDATA_INTERNAL_CHECKS
  1404. long int entries = dict->entries;
  1405. long int referenced_items = dict->referenced_items;
  1406. long int pending_deletion_items = dict->pending_deletion_items;
  1407. const char *creation_function = dict->creation_function;
  1408. const char *creation_file = dict->creation_file;
  1409. size_t creation_line = dict->creation_line;
  1410. #endif
  1411. // destroy the index
  1412. dictionary_index_lock_wrlock(dict);
  1413. index_size += hashtable_destroy_unsafe(dict);
  1414. dictionary_index_wrlock_unlock(dict);
  1415. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  1416. DICTIONARY_ITEM *item = dict->items.list;
  1417. while (item) {
  1418. // cache item->next
  1419. // because we are going to free item
  1420. DICTIONARY_ITEM *item_next = item->next;
  1421. item_size += dict_item_free_with_hooks(dict, item);
  1422. item = item_next;
  1423. // to speed up destruction, we don't
  1424. // unlink item from the linked-list here
  1425. counted_items++;
  1426. }
  1427. dict->items.list = NULL;
  1428. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  1429. dict_size += dictionary_locks_destroy(dict);
  1430. dict_size += reference_counter_free(dict);
  1431. dict_size += dictionary_hooks_free(dict);
  1432. dict_size += sizeof(DICTIONARY);
  1433. DICTIONARY_STATS_MINUS_MEMORY(dict, 0, sizeof(DICTIONARY), 0);
  1434. if(dict->value_aral)
  1435. aral_by_size_release(dict->value_aral);
  1436. freez(dict);
  1437. internal_error(
  1438. false,
  1439. "DICTIONARY: Freed dictionary created from %s() %zu@%s, having %ld (counted %zu) entries, %ld referenced, %ld pending deletion, total freed memory: %zu bytes (sizeof(dict) = %zu, sizeof(item) = %zu).",
  1440. creation_function,
  1441. creation_line,
  1442. creation_file,
  1443. entries, counted_items, referenced_items, pending_deletion_items,
  1444. dict_size + item_size, sizeof(DICTIONARY), sizeof(DICTIONARY_ITEM) + sizeof(DICTIONARY_ITEM_SHARED));
  1445. if(mem)
  1446. *mem = dict_size + item_size + index_size;
  1447. return true;
  1448. }
  1449. netdata_mutex_t dictionaries_waiting_to_be_destroyed_mutex = NETDATA_MUTEX_INITIALIZER;
  1450. static DICTIONARY *dictionaries_waiting_to_be_destroyed = NULL;
  1451. void dictionary_queue_for_destruction(DICTIONARY *dict) {
  1452. if(is_dictionary_destroyed(dict))
  1453. return;
  1454. DICTIONARY_STATS_DICT_DESTROY_QUEUED_PLUS1(dict);
  1455. dict_flag_set(dict, DICT_FLAG_DESTROYED);
  1456. netdata_mutex_lock(&dictionaries_waiting_to_be_destroyed_mutex);
  1457. dict->next = dictionaries_waiting_to_be_destroyed;
  1458. dictionaries_waiting_to_be_destroyed = dict;
  1459. netdata_mutex_unlock(&dictionaries_waiting_to_be_destroyed_mutex);
  1460. }
  1461. void cleanup_destroyed_dictionaries(void) {
  1462. if(!dictionaries_waiting_to_be_destroyed)
  1463. return;
  1464. netdata_mutex_lock(&dictionaries_waiting_to_be_destroyed_mutex);
  1465. DICTIONARY *dict, *last = NULL, *next = NULL;
  1466. for(dict = dictionaries_waiting_to_be_destroyed; dict ; dict = next) {
  1467. next = dict->next;
  1468. #ifdef NETDATA_INTERNAL_CHECKS
  1469. size_t line = dict->creation_line;
  1470. const char *file = dict->creation_file;
  1471. const char *function = dict->creation_function;
  1472. pid_t pid = dict->creation_tid;
  1473. #endif
  1474. DICTIONARY_STATS_DICT_DESTROY_QUEUED_MINUS1(dict);
  1475. if(dictionary_free_all_resources(dict, NULL, false)) {
  1476. internal_error(
  1477. true,
  1478. "DICTIONARY: freed dictionary with delayed destruction, created from %s() %zu@%s pid %d.",
  1479. function, line, file, pid);
  1480. if(last) last->next = next;
  1481. else dictionaries_waiting_to_be_destroyed = next;
  1482. }
  1483. else {
  1484. internal_error(
  1485. true,
  1486. "DICTIONARY: cannot free dictionary with delayed destruction, created from %s() %zu@%s pid %d.",
  1487. function, line, file, pid);
  1488. DICTIONARY_STATS_DICT_DESTROY_QUEUED_PLUS1(dict);
  1489. last = dict;
  1490. }
  1491. }
  1492. netdata_mutex_unlock(&dictionaries_waiting_to_be_destroyed_mutex);
  1493. }
  1494. // ----------------------------------------------------------------------------
  1495. // API internal checks
  1496. #ifdef NETDATA_INTERNAL_CHECKS
  1497. #define api_internal_check(dict, item, allow_null_dict, allow_null_item) api_internal_check_with_trace(dict, item, __FUNCTION__, allow_null_dict, allow_null_item)
  1498. static inline void api_internal_check_with_trace(DICTIONARY *dict, DICTIONARY_ITEM *item, const char *function, bool allow_null_dict, bool allow_null_item) {
  1499. if(!allow_null_dict && !dict) {
  1500. internal_error(
  1501. item,
  1502. "DICTIONARY: attempted to %s() with a NULL dictionary, passing an item created from %s() %zu@%s.",
  1503. function,
  1504. item->dict->creation_function,
  1505. item->dict->creation_line,
  1506. item->dict->creation_file);
  1507. fatal("DICTIONARY: attempted to %s() but dict is NULL", function);
  1508. }
  1509. if(!allow_null_item && !item) {
  1510. internal_error(
  1511. true,
  1512. "DICTIONARY: attempted to %s() without an item on a dictionary created from %s() %zu@%s.",
  1513. function,
  1514. dict?dict->creation_function:"unknown",
  1515. dict?dict->creation_line:0,
  1516. dict?dict->creation_file:"unknown");
  1517. fatal("DICTIONARY: attempted to %s() but item is NULL", function);
  1518. }
  1519. if(dict && item && dict != item->dict) {
  1520. internal_error(
  1521. true,
  1522. "DICTIONARY: attempted to %s() an item on a dictionary created from %s() %zu@%s, but the item belongs to the dictionary created from %s() %zu@%s.",
  1523. function,
  1524. dict->creation_function,
  1525. dict->creation_line,
  1526. dict->creation_file,
  1527. item->dict->creation_function,
  1528. item->dict->creation_line,
  1529. item->dict->creation_file
  1530. );
  1531. fatal("DICTIONARY: %s(): item does not belong to this dictionary.", function);
  1532. }
  1533. if(item) {
  1534. REFCOUNT refcount = DICTIONARY_ITEM_REFCOUNT_GET(dict, item);
  1535. if (unlikely(refcount <= 0)) {
  1536. internal_error(
  1537. true,
  1538. "DICTIONARY: attempted to %s() of an item with reference counter = %d on a dictionary created from %s() %zu@%s",
  1539. function,
  1540. refcount,
  1541. item->dict->creation_function,
  1542. item->dict->creation_line,
  1543. item->dict->creation_file);
  1544. fatal("DICTIONARY: attempted to %s but item is having refcount = %d", function, refcount);
  1545. }
  1546. }
  1547. }
  1548. #else
  1549. #define api_internal_check(dict, item, allow_null_dict, allow_null_item) debug_dummy()
  1550. #endif
  1551. #define api_is_name_good(dict, name, name_len) api_is_name_good_with_trace(dict, name, name_len, __FUNCTION__)
  1552. static bool api_is_name_good_with_trace(DICTIONARY *dict __maybe_unused, const char *name, ssize_t name_len __maybe_unused, const char *function __maybe_unused) {
  1553. if(unlikely(!name)) {
  1554. internal_error(
  1555. true,
  1556. "DICTIONARY: attempted to %s() with name = NULL on a dictionary created from %s() %zu@%s.",
  1557. function,
  1558. dict?dict->creation_function:"unknown",
  1559. dict?dict->creation_line:0,
  1560. dict?dict->creation_file:"unknown");
  1561. return false;
  1562. }
  1563. if(unlikely(!*name)) {
  1564. internal_error(
  1565. true,
  1566. "DICTIONARY: attempted to %s() with empty name on a dictionary created from %s() %zu@%s.",
  1567. function,
  1568. dict?dict->creation_function:"unknown",
  1569. dict?dict->creation_line:0,
  1570. dict?dict->creation_file:"unknown");
  1571. return false;
  1572. }
  1573. internal_error(
  1574. name_len > 0 && name_len != (ssize_t)(strlen(name) + 1),
  1575. "DICTIONARY: attempted to %s() with a name of '%s', having length of %zu (incl. '\\0'), but the supplied name_len = %ld, on a dictionary created from %s() %zu@%s.",
  1576. function,
  1577. name,
  1578. strlen(name) + 1,
  1579. (long int) name_len,
  1580. dict?dict->creation_function:"unknown",
  1581. dict?dict->creation_line:0,
  1582. dict?dict->creation_file:"unknown");
  1583. internal_error(
  1584. name_len <= 0 && name_len != -1,
  1585. "DICTIONARY: attempted to %s() with a name of '%s', having length of %zu (incl. '\\0'), but the supplied name_len = %ld, on a dictionary created from %s() %zu@%s.",
  1586. function,
  1587. name,
  1588. strlen(name) + 1,
  1589. (long int) name_len,
  1590. dict?dict->creation_function:"unknown",
  1591. dict?dict->creation_line:0,
  1592. dict?dict->creation_file:"unknown");
  1593. return true;
  1594. }
  1595. // ----------------------------------------------------------------------------
  1596. // API - dictionary management
  1597. static DICTIONARY *dictionary_create_internal(DICT_OPTIONS options, struct dictionary_stats *stats, size_t fixed_size) {
  1598. cleanup_destroyed_dictionaries();
  1599. DICTIONARY *dict = callocz(1, sizeof(DICTIONARY));
  1600. dict->options = options;
  1601. dict->stats = stats;
  1602. if((dict->options & DICT_OPTION_FIXED_SIZE) && !fixed_size) {
  1603. dict->options &= ~DICT_OPTION_FIXED_SIZE;
  1604. internal_fatal(true, "DICTIONARY: requested fixed size dictionary, without setting the size");
  1605. }
  1606. if(!(dict->options & DICT_OPTION_FIXED_SIZE) && fixed_size) {
  1607. dict->options |= DICT_OPTION_FIXED_SIZE;
  1608. internal_fatal(true, "DICTIONARY: set a fixed size for the items, without setting DICT_OPTION_FIXED_SIZE flag");
  1609. }
  1610. if(dict->options & DICT_OPTION_FIXED_SIZE)
  1611. dict->value_aral = aral_by_size_acquire(fixed_size);
  1612. else
  1613. dict->value_aral = NULL;
  1614. size_t dict_size = 0;
  1615. dict_size += sizeof(DICTIONARY);
  1616. dict_size += dictionary_locks_init(dict);
  1617. dict_size += reference_counter_init(dict);
  1618. dict_size += hashtable_init_unsafe(dict);
  1619. dictionary_static_items_aral_init();
  1620. pointer_index_init(dict);
  1621. DICTIONARY_STATS_PLUS_MEMORY(dict, 0, dict_size, 0);
  1622. return dict;
  1623. }
  1624. #ifdef NETDATA_INTERNAL_CHECKS
  1625. DICTIONARY *dictionary_create_advanced_with_trace(DICT_OPTIONS options, struct dictionary_stats *stats, size_t fixed_size, const char *function, size_t line, const char *file) {
  1626. #else
  1627. DICTIONARY *dictionary_create_advanced(DICT_OPTIONS options, struct dictionary_stats *stats, size_t fixed_size) {
  1628. #endif
  1629. DICTIONARY *dict = dictionary_create_internal(options, stats?stats:&dictionary_stats_category_other, fixed_size);
  1630. #ifdef NETDATA_INTERNAL_CHECKS
  1631. dict->creation_function = function;
  1632. dict->creation_file = file;
  1633. dict->creation_line = line;
  1634. #endif
  1635. DICTIONARY_STATS_DICT_CREATIONS_PLUS1(dict);
  1636. return dict;
  1637. }
  1638. #ifdef NETDATA_INTERNAL_CHECKS
  1639. DICTIONARY *dictionary_create_view_with_trace(DICTIONARY *master, const char *function, size_t line, const char *file) {
  1640. #else
  1641. DICTIONARY *dictionary_create_view(DICTIONARY *master) {
  1642. #endif
  1643. DICTIONARY *dict = dictionary_create_internal(master->options, master->stats,
  1644. master->value_aral ? aral_element_size(master->value_aral) : 0);
  1645. dict->master = master;
  1646. dictionary_hooks_allocate(master);
  1647. if(unlikely(__atomic_load_n(&master->hooks->links, __ATOMIC_RELAXED)) < 1)
  1648. fatal("DICTIONARY: attempted to create a view that has %d links", master->hooks->links);
  1649. dict->hooks = master->hooks;
  1650. __atomic_add_fetch(&master->hooks->links, 1, __ATOMIC_ACQUIRE);
  1651. #ifdef NETDATA_INTERNAL_CHECKS
  1652. dict->creation_function = function;
  1653. dict->creation_file = file;
  1654. dict->creation_line = line;
  1655. dict->creation_tid = gettid();
  1656. #endif
  1657. DICTIONARY_STATS_DICT_CREATIONS_PLUS1(dict);
  1658. return dict;
  1659. }
  1660. void dictionary_flush(DICTIONARY *dict) {
  1661. if(unlikely(!dict))
  1662. return;
  1663. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  1664. DICTIONARY_ITEM *item, *next = NULL;
  1665. for(item = dict->items.list; item ;item = next) {
  1666. next = item->next;
  1667. dict_item_del(dict, item_get_name(item), (ssize_t) item_get_name_len(item) + 1);
  1668. }
  1669. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  1670. DICTIONARY_STATS_DICT_FLUSHES_PLUS1(dict);
  1671. }
  1672. size_t dictionary_destroy(DICTIONARY *dict) {
  1673. cleanup_destroyed_dictionaries();
  1674. if(!dict) return 0;
  1675. ll_recursive_lock(dict, DICTIONARY_LOCK_WRITE);
  1676. dict_flag_set(dict, DICT_FLAG_DESTROYED);
  1677. DICTIONARY_STATS_DICT_DESTRUCTIONS_PLUS1(dict);
  1678. size_t referenced_items = dictionary_referenced_items(dict);
  1679. if(referenced_items) {
  1680. dictionary_flush(dict);
  1681. dictionary_queue_for_destruction(dict);
  1682. internal_error(
  1683. true,
  1684. "DICTIONARY: delaying destruction of dictionary created from %s() %zu@%s, because it has %d referenced items in it (%d total).",
  1685. dict->creation_function,
  1686. dict->creation_line,
  1687. dict->creation_file,
  1688. dict->referenced_items,
  1689. dict->entries);
  1690. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  1691. return 0;
  1692. }
  1693. ll_recursive_unlock(dict, DICTIONARY_LOCK_WRITE);
  1694. size_t freed;
  1695. dictionary_free_all_resources(dict, &freed, true);
  1696. return freed;
  1697. }
  1698. // ----------------------------------------------------------------------------
  1699. // SET an item to the dictionary
  1700. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_set_and_acquire_item_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, void *value, size_t value_len, void *constructor_data) {
  1701. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1702. return NULL;
  1703. api_internal_check(dict, NULL, false, true);
  1704. if(unlikely(is_view_dictionary(dict)))
  1705. fatal("DICTIONARY: this dictionary is a view, you cannot add items other than the ones from the master dictionary.");
  1706. DICTIONARY_ITEM *item =
  1707. dict_item_add_or_reset_value_and_acquire(dict, name, name_len, value, value_len, constructor_data, NULL);
  1708. api_internal_check(dict, item, false, false);
  1709. return item;
  1710. }
  1711. void *dictionary_set_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, void *value, size_t value_len, void *constructor_data) {
  1712. DICTIONARY_ITEM *item = dictionary_set_and_acquire_item_advanced(dict, name, name_len, value, value_len, constructor_data);
  1713. if(likely(item)) {
  1714. void *v = item->shared->value;
  1715. item_release(dict, item);
  1716. return v;
  1717. }
  1718. return NULL;
  1719. }
  1720. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_view_set_and_acquire_item_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, DICTIONARY_ITEM *master_item) {
  1721. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1722. return NULL;
  1723. api_internal_check(dict, NULL, false, true);
  1724. if(unlikely(is_master_dictionary(dict)))
  1725. fatal("DICTIONARY: this dictionary is a master, you cannot add items from other dictionaries.");
  1726. garbage_collect_pending_deletes(dict);
  1727. dictionary_acquired_item_dup(dict->master, master_item);
  1728. DICTIONARY_ITEM *item = dict_item_add_or_reset_value_and_acquire(dict, name, name_len, NULL, 0, NULL, master_item);
  1729. dictionary_acquired_item_release(dict->master, master_item);
  1730. api_internal_check(dict, item, false, false);
  1731. return item;
  1732. }
  1733. void *dictionary_view_set_advanced(DICTIONARY *dict, const char *name, ssize_t name_len, DICTIONARY_ITEM *master_item) {
  1734. DICTIONARY_ITEM *item = dictionary_view_set_and_acquire_item_advanced(dict, name, name_len, master_item);
  1735. if(likely(item)) {
  1736. void *v = item->shared->value;
  1737. item_release(dict, item);
  1738. return v;
  1739. }
  1740. return NULL;
  1741. }
  1742. // ----------------------------------------------------------------------------
  1743. // GET an item from the dictionary
  1744. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_get_and_acquire_item_advanced(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1745. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1746. return NULL;
  1747. api_internal_check(dict, NULL, false, true);
  1748. DICTIONARY_ITEM *item = dict_item_find_and_acquire(dict, name, name_len);
  1749. api_internal_check(dict, item, false, true);
  1750. return item;
  1751. }
  1752. void *dictionary_get_advanced(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1753. DICTIONARY_ITEM *item = dictionary_get_and_acquire_item_advanced(dict, name, name_len);
  1754. if(likely(item)) {
  1755. void *v = item->shared->value;
  1756. item_release(dict, item);
  1757. return v;
  1758. }
  1759. return NULL;
  1760. }
  1761. // ----------------------------------------------------------------------------
  1762. // DUP/REL an item (increase/decrease its reference counter)
  1763. DICT_ITEM_CONST DICTIONARY_ITEM *dictionary_acquired_item_dup(DICTIONARY *dict, DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1764. // we allow the item to be NULL here
  1765. api_internal_check(dict, item, false, true);
  1766. if(likely(item)) {
  1767. item_acquire(dict, item);
  1768. api_internal_check(dict, item, false, false);
  1769. }
  1770. return item;
  1771. }
  1772. void dictionary_acquired_item_release(DICTIONARY *dict, DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1773. // we allow the item to be NULL here
  1774. api_internal_check(dict, item, false, true);
  1775. // no need to get a lock here
  1776. // we pass the last parameter to reference_counter_release() as true
  1777. // so that the release may get a write-lock if required to clean up
  1778. if(likely(item))
  1779. item_release(dict, item);
  1780. }
  1781. // ----------------------------------------------------------------------------
  1782. // get the name/value of an item
  1783. const char *dictionary_acquired_item_name(DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1784. return item_get_name(item);
  1785. }
  1786. void *dictionary_acquired_item_value(DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1787. if(likely(item))
  1788. return item->shared->value;
  1789. return NULL;
  1790. }
  1791. size_t dictionary_acquired_item_references(DICT_ITEM_CONST DICTIONARY_ITEM *item) {
  1792. if(likely(item))
  1793. return DICTIONARY_ITEM_REFCOUNT_GET_SOLE(item);
  1794. return 0;
  1795. }
  1796. // ----------------------------------------------------------------------------
  1797. // DEL an item
  1798. bool dictionary_del_advanced(DICTIONARY *dict, const char *name, ssize_t name_len) {
  1799. if(unlikely(!api_is_name_good(dict, name, name_len)))
  1800. return false;
  1801. api_internal_check(dict, NULL, false, true);
  1802. if(unlikely(is_dictionary_destroyed(dict))) {
  1803. internal_error(true, "DICTIONARY: attempted to delete item on a destroyed dictionary");
  1804. return false;
  1805. }
  1806. return dict_item_del(dict, name, name_len);
  1807. }
  1808. // ----------------------------------------------------------------------------
  1809. // traversal with loop
  1810. void *dictionary_foreach_start_rw(DICTFE *dfe, DICTIONARY *dict, char rw) {
  1811. if(unlikely(!dfe || !dict)) return NULL;
  1812. DICTIONARY_STATS_TRAVERSALS_PLUS1(dict);
  1813. if(unlikely(is_dictionary_destroyed(dict))) {
  1814. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_start_rw() on a destroyed dictionary");
  1815. dfe->counter = 0;
  1816. dfe->item = NULL;
  1817. dfe->name = NULL;
  1818. dfe->value = NULL;
  1819. return NULL;
  1820. }
  1821. dfe->counter = 0;
  1822. dfe->dict = dict;
  1823. dfe->rw = rw;
  1824. dfe->locked = true;
  1825. ll_recursive_lock(dict, dfe->rw);
  1826. // get the first item from the list
  1827. DICTIONARY_ITEM *item = dict->items.list;
  1828. // skip all the deleted items
  1829. while(item && !item_check_and_acquire(dict, item))
  1830. item = item->next;
  1831. if(likely(item)) {
  1832. dfe->item = item;
  1833. dfe->name = (char *)item_get_name(item);
  1834. dfe->value = item->shared->value;
  1835. }
  1836. else {
  1837. dfe->item = NULL;
  1838. dfe->name = NULL;
  1839. dfe->value = NULL;
  1840. }
  1841. if(unlikely(dfe->rw == DICTIONARY_LOCK_REENTRANT)) {
  1842. ll_recursive_unlock(dfe->dict, dfe->rw);
  1843. dfe->locked = false;
  1844. }
  1845. return dfe->value;
  1846. }
  1847. void *dictionary_foreach_next(DICTFE *dfe) {
  1848. if(unlikely(!dfe || !dfe->dict)) return NULL;
  1849. if(unlikely(is_dictionary_destroyed(dfe->dict))) {
  1850. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_next() on a destroyed dictionary");
  1851. dfe->item = NULL;
  1852. dfe->name = NULL;
  1853. dfe->value = NULL;
  1854. return NULL;
  1855. }
  1856. if(unlikely(dfe->rw == DICTIONARY_LOCK_REENTRANT) || !dfe->locked) {
  1857. ll_recursive_lock(dfe->dict, dfe->rw);
  1858. dfe->locked = true;
  1859. }
  1860. // the item we just did
  1861. DICTIONARY_ITEM *item = dfe->item;
  1862. // get the next item from the list
  1863. DICTIONARY_ITEM *item_next = (item) ? item->next : NULL;
  1864. // skip all the deleted items until one that can be acquired is found
  1865. while(item_next && !item_check_and_acquire(dfe->dict, item_next))
  1866. item_next = item_next->next;
  1867. if(likely(item)) {
  1868. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dfe->dict, item, dfe->rw);
  1869. // item_release(dfe->dict, item);
  1870. }
  1871. item = item_next;
  1872. if(likely(item)) {
  1873. dfe->item = item;
  1874. dfe->name = (char *)item_get_name(item);
  1875. dfe->value = item->shared->value;
  1876. dfe->counter++;
  1877. }
  1878. else {
  1879. dfe->item = NULL;
  1880. dfe->name = NULL;
  1881. dfe->value = NULL;
  1882. }
  1883. if(unlikely(dfe->rw == DICTIONARY_LOCK_REENTRANT)) {
  1884. ll_recursive_unlock(dfe->dict, dfe->rw);
  1885. dfe->locked = false;
  1886. }
  1887. return dfe->value;
  1888. }
  1889. void dictionary_foreach_unlock(DICTFE *dfe) {
  1890. if(dfe->locked) {
  1891. ll_recursive_unlock(dfe->dict, dfe->rw);
  1892. dfe->locked = false;
  1893. }
  1894. }
  1895. void dictionary_foreach_done(DICTFE *dfe) {
  1896. if(unlikely(!dfe || !dfe->dict)) return;
  1897. if(unlikely(is_dictionary_destroyed(dfe->dict))) {
  1898. internal_error(true, "DICTIONARY: attempted to dictionary_foreach_next() on a destroyed dictionary");
  1899. return;
  1900. }
  1901. // the item we just did
  1902. DICTIONARY_ITEM *item = dfe->item;
  1903. // release it, so that it can possibly be deleted
  1904. if(likely(item)) {
  1905. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dfe->dict, item, dfe->rw);
  1906. // item_release(dfe->dict, item);
  1907. }
  1908. if(likely(dfe->rw != DICTIONARY_LOCK_REENTRANT) && dfe->locked) {
  1909. ll_recursive_unlock(dfe->dict, dfe->rw);
  1910. dfe->locked = false;
  1911. }
  1912. dfe->dict = NULL;
  1913. dfe->item = NULL;
  1914. dfe->name = NULL;
  1915. dfe->value = NULL;
  1916. dfe->counter = 0;
  1917. }
  1918. // ----------------------------------------------------------------------------
  1919. // API - walk through the dictionary.
  1920. // The dictionary is locked for reading while this happens
  1921. // do not use other dictionary calls while walking the dictionary - deadlock!
  1922. int dictionary_walkthrough_rw(DICTIONARY *dict, char rw, int (*callback)(const DICTIONARY_ITEM *item, void *entry, void *data), void *data) {
  1923. if(unlikely(!dict || !callback)) return 0;
  1924. if(unlikely(is_dictionary_destroyed(dict))) {
  1925. internal_error(true, "DICTIONARY: attempted to dictionary_walkthrough_rw() on a destroyed dictionary");
  1926. return 0;
  1927. }
  1928. ll_recursive_lock(dict, rw);
  1929. DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict);
  1930. // written in such a way, that the callback can delete the active element
  1931. int ret = 0;
  1932. DICTIONARY_ITEM *item = dict->items.list, *item_next;
  1933. while(item) {
  1934. // skip the deleted items
  1935. if(unlikely(!item_check_and_acquire(dict, item))) {
  1936. item = item->next;
  1937. continue;
  1938. }
  1939. if(unlikely(rw == DICTIONARY_LOCK_REENTRANT))
  1940. ll_recursive_unlock(dict, rw);
  1941. int r = callback(item, item->shared->value, data);
  1942. if(unlikely(rw == DICTIONARY_LOCK_REENTRANT))
  1943. ll_recursive_lock(dict, rw);
  1944. // since we have a reference counter, this item cannot be deleted
  1945. // until we release the reference counter, so the pointers are there
  1946. item_next = item->next;
  1947. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dict, item, rw);
  1948. // item_release(dict, item);
  1949. if(unlikely(r < 0)) {
  1950. ret = r;
  1951. break;
  1952. }
  1953. ret += r;
  1954. item = item_next;
  1955. }
  1956. ll_recursive_unlock(dict, rw);
  1957. return ret;
  1958. }
  1959. // ----------------------------------------------------------------------------
  1960. // sorted walkthrough
  1961. typedef int (*qsort_compar)(const void *item1, const void *item2);
  1962. static int dictionary_sort_compar(const void *item1, const void *item2) {
  1963. return strcmp(item_get_name((*(DICTIONARY_ITEM **)item1)), item_get_name((*(DICTIONARY_ITEM **)item2)));
  1964. }
  1965. int dictionary_sorted_walkthrough_rw(DICTIONARY *dict, char rw, int (*callback)(const DICTIONARY_ITEM *item, void *entry, void *data), void *data, dictionary_sorted_compar compar) {
  1966. if(unlikely(!dict || !callback)) return 0;
  1967. if(unlikely(is_dictionary_destroyed(dict))) {
  1968. internal_error(true, "DICTIONARY: attempted to dictionary_sorted_walkthrough_rw() on a destroyed dictionary");
  1969. return 0;
  1970. }
  1971. DICTIONARY_STATS_WALKTHROUGHS_PLUS1(dict);
  1972. ll_recursive_lock(dict, rw);
  1973. size_t entries = __atomic_load_n(&dict->entries, __ATOMIC_RELAXED);
  1974. DICTIONARY_ITEM **array = mallocz(sizeof(DICTIONARY_ITEM *) * entries);
  1975. size_t i;
  1976. DICTIONARY_ITEM *item;
  1977. for(item = dict->items.list, i = 0; item && i < entries; item = item->next) {
  1978. if(likely(item_check_and_acquire(dict, item)))
  1979. array[i++] = item;
  1980. }
  1981. ll_recursive_unlock(dict, rw);
  1982. if(unlikely(i != entries))
  1983. entries = i;
  1984. if(compar)
  1985. qsort(array, entries, sizeof(DICTIONARY_ITEM *), (qsort_compar)compar);
  1986. else
  1987. qsort(array, entries, sizeof(DICTIONARY_ITEM *), dictionary_sort_compar);
  1988. bool callit = true;
  1989. int ret = 0, r;
  1990. for(i = 0; i < entries ;i++) {
  1991. item = array[i];
  1992. if(callit)
  1993. r = callback(item, item->shared->value, data);
  1994. dict_item_release_and_check_if_it_is_deleted_and_can_be_removed_under_this_lock_mode(dict, item, rw);
  1995. // item_release(dict, item);
  1996. if(r < 0) {
  1997. ret = r;
  1998. r = 0;
  1999. // stop calling the callback,
  2000. // but we have to continue, to release all the reference counters
  2001. callit = false;
  2002. }
  2003. else
  2004. ret += r;
  2005. }
  2006. freez(array);
  2007. return ret;
  2008. }
  2009. // ----------------------------------------------------------------------------
  2010. // THREAD_CACHE
  2011. static __thread Pvoid_t thread_cache_judy_array = NULL;
  2012. void *thread_cache_entry_get_or_set(void *key,
  2013. ssize_t key_length,
  2014. void *value,
  2015. void *(*transform_the_value_before_insert)(void *key, size_t key_length, void *value)
  2016. ) {
  2017. if(unlikely(!key || !key_length)) return NULL;
  2018. if(key_length == -1)
  2019. key_length = (ssize_t)strlen((char *)key) + 1;
  2020. JError_t J_Error;
  2021. Pvoid_t *Rc = JudyHSIns(&thread_cache_judy_array, key, key_length, &J_Error);
  2022. if (unlikely(Rc == PJERR)) {
  2023. fatal("THREAD_CACHE: Cannot insert entry to JudyHS, JU_ERRNO_* == %u, ID == %d",
  2024. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  2025. }
  2026. if(*Rc == 0) {
  2027. // new item added
  2028. *Rc = (transform_the_value_before_insert) ? transform_the_value_before_insert(key, key_length, value) : value;
  2029. }
  2030. return *Rc;
  2031. }
  2032. void thread_cache_destroy(void) {
  2033. if(unlikely(!thread_cache_judy_array)) return;
  2034. JError_t J_Error;
  2035. Word_t ret = JudyHSFreeArray(&thread_cache_judy_array, &J_Error);
  2036. if(unlikely(ret == (Word_t) JERR)) {
  2037. netdata_log_error("THREAD_CACHE: Cannot destroy JudyHS, JU_ERRNO_* == %u, ID == %d",
  2038. JU_ERRNO(&J_Error), JU_ERRID(&J_Error));
  2039. }
  2040. internal_error(true, "THREAD_CACHE: hash table freed %lu bytes", ret);
  2041. thread_cache_judy_array = NULL;
  2042. }
  2043. // ----------------------------------------------------------------------------
  2044. // unit test
  2045. static void dictionary_unittest_free_char_pp(char **pp, size_t entries) {
  2046. for(size_t i = 0; i < entries ;i++)
  2047. freez(pp[i]);
  2048. freez(pp);
  2049. }
  2050. static char **dictionary_unittest_generate_names(size_t entries) {
  2051. char **names = mallocz(sizeof(char *) * entries);
  2052. for(size_t i = 0; i < entries ;i++) {
  2053. char buf[25 + 1] = "";
  2054. snprintfz(buf, sizeof(buf) - 1, "name.%zu.0123456789.%zu!@#$%%^&*(),./[]{}\\|~`", i, entries / 2 + i);
  2055. names[i] = strdupz(buf);
  2056. }
  2057. return names;
  2058. }
  2059. static char **dictionary_unittest_generate_values(size_t entries) {
  2060. char **values = mallocz(sizeof(char *) * entries);
  2061. for(size_t i = 0; i < entries ;i++) {
  2062. char buf[25 + 1] = "";
  2063. snprintfz(buf, sizeof(buf) - 1, "value-%zu-0987654321.%zu%%^&*(),. \t !@#$/[]{}\\|~`", i, entries / 2 + i);
  2064. values[i] = strdupz(buf);
  2065. }
  2066. return values;
  2067. }
  2068. static size_t dictionary_unittest_set_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2069. size_t errors = 0;
  2070. for(size_t i = 0; i < entries ;i++) {
  2071. size_t vallen = strlen(values[i]) + 1;
  2072. char *val = (char *)dictionary_set(dict, names[i], values[i], vallen);
  2073. if(val == values[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  2074. if(!val || memcmp(val, values[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2075. }
  2076. return errors;
  2077. }
  2078. static size_t dictionary_unittest_set_null(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2079. (void)values;
  2080. size_t errors = 0;
  2081. size_t i = 0;
  2082. for(; i < entries ;i++) {
  2083. void *val = dictionary_set(dict, names[i], NULL, 0);
  2084. if(val != NULL) { fprintf(stderr, ">>> %s() returns a non NULL value\n", __FUNCTION__); errors++; }
  2085. }
  2086. if(dictionary_entries(dict) != i) {
  2087. fprintf(stderr, ">>> %s() dictionary items do not match\n", __FUNCTION__);
  2088. errors++;
  2089. }
  2090. return errors;
  2091. }
  2092. static size_t dictionary_unittest_set_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2093. size_t errors = 0;
  2094. for(size_t i = 0; i < entries ;i++) {
  2095. size_t vallen = strlen(values[i]) + 1;
  2096. char *val = (char *)dictionary_set(dict, names[i], values[i], vallen);
  2097. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2098. }
  2099. return errors;
  2100. }
  2101. static size_t dictionary_unittest_get_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2102. size_t errors = 0;
  2103. for(size_t i = 0; i < entries ;i++) {
  2104. size_t vallen = strlen(values[i]) + 1;
  2105. char *val = (char *)dictionary_get(dict, names[i]);
  2106. if(val == values[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  2107. if(!val || memcmp(val, values[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2108. }
  2109. return errors;
  2110. }
  2111. static size_t dictionary_unittest_get_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2112. size_t errors = 0;
  2113. for(size_t i = 0; i < entries ;i++) {
  2114. char *val = (char *)dictionary_get(dict, names[i]);
  2115. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2116. }
  2117. return errors;
  2118. }
  2119. static size_t dictionary_unittest_get_nonexisting(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2120. (void)names;
  2121. size_t errors = 0;
  2122. for(size_t i = 0; i < entries ;i++) {
  2123. char *val = (char *)dictionary_get(dict, values[i]);
  2124. if(val) { fprintf(stderr, ">>> %s() returns non-existing item\n", __FUNCTION__); errors++; }
  2125. }
  2126. return errors;
  2127. }
  2128. static size_t dictionary_unittest_del_nonexisting(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2129. (void)names;
  2130. size_t errors = 0;
  2131. for(size_t i = 0; i < entries ;i++) {
  2132. bool ret = dictionary_del(dict, values[i]);
  2133. if(ret) { fprintf(stderr, ">>> %s() deleted non-existing item\n", __FUNCTION__); errors++; }
  2134. }
  2135. return errors;
  2136. }
  2137. static size_t dictionary_unittest_del_existing(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2138. (void)values;
  2139. size_t errors = 0;
  2140. size_t forward_from = 0, forward_to = entries / 3;
  2141. size_t middle_from = forward_to, middle_to = entries * 2 / 3;
  2142. size_t backward_from = middle_to, backward_to = entries;
  2143. for(size_t i = forward_from; i < forward_to ;i++) {
  2144. bool ret = dictionary_del(dict, names[i]);
  2145. if(!ret) { fprintf(stderr, ">>> %s() didn't delete (forward) existing item\n", __FUNCTION__); errors++; }
  2146. }
  2147. for(size_t i = middle_to - 1; i >= middle_from ;i--) {
  2148. bool ret = dictionary_del(dict, names[i]);
  2149. if(!ret) { fprintf(stderr, ">>> %s() didn't delete (middle) existing item\n", __FUNCTION__); errors++; }
  2150. }
  2151. for(size_t i = backward_to - 1; i >= backward_from ;i--) {
  2152. bool ret = dictionary_del(dict, names[i]);
  2153. if(!ret) { fprintf(stderr, ">>> %s() didn't delete (backward) existing item\n", __FUNCTION__); errors++; }
  2154. }
  2155. return errors;
  2156. }
  2157. static size_t dictionary_unittest_reset_clone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2158. (void)values;
  2159. // set the name as value too
  2160. size_t errors = 0;
  2161. for(size_t i = 0; i < entries ;i++) {
  2162. size_t vallen = strlen(names[i]) + 1;
  2163. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  2164. if(val == names[i]) { fprintf(stderr, ">>> %s() returns reference to value\n", __FUNCTION__); errors++; }
  2165. if(!val || memcmp(val, names[i], vallen) != 0) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2166. }
  2167. return errors;
  2168. }
  2169. static size_t dictionary_unittest_reset_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2170. (void)values;
  2171. // set the name as value too
  2172. size_t errors = 0;
  2173. for(size_t i = 0; i < entries ;i++) {
  2174. size_t vallen = strlen(names[i]) + 1;
  2175. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  2176. if(val != names[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2177. if(!val) { fprintf(stderr, ">>> %s() returns invalid value\n", __FUNCTION__); errors++; }
  2178. }
  2179. return errors;
  2180. }
  2181. static size_t dictionary_unittest_reset_dont_overwrite_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2182. // set the name as value too
  2183. size_t errors = 0;
  2184. for(size_t i = 0; i < entries ;i++) {
  2185. size_t vallen = strlen(names[i]) + 1;
  2186. char *val = (char *)dictionary_set(dict, names[i], names[i], vallen);
  2187. if(val != values[i]) { fprintf(stderr, ">>> %s() returns invalid pointer to value\n", __FUNCTION__); errors++; }
  2188. }
  2189. return errors;
  2190. }
  2191. static int dictionary_unittest_walkthrough_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value __maybe_unused, void *data __maybe_unused) {
  2192. return 1;
  2193. }
  2194. static size_t dictionary_unittest_walkthrough(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2195. (void)names;
  2196. (void)values;
  2197. int sum = dictionary_walkthrough_read(dict, dictionary_unittest_walkthrough_callback, NULL);
  2198. if(sum < (int)entries) return entries - sum;
  2199. else return sum - entries;
  2200. }
  2201. static int dictionary_unittest_walkthrough_delete_this_callback(const DICTIONARY_ITEM *item, void *value __maybe_unused, void *data) {
  2202. const char *name = dictionary_acquired_item_name((DICTIONARY_ITEM *)item);
  2203. if(!dictionary_del((DICTIONARY *)data, name))
  2204. return 0;
  2205. return 1;
  2206. }
  2207. static size_t dictionary_unittest_walkthrough_delete_this(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2208. (void)names;
  2209. (void)values;
  2210. int sum = dictionary_walkthrough_write(dict, dictionary_unittest_walkthrough_delete_this_callback, dict);
  2211. if(sum < (int)entries) return entries - sum;
  2212. else return sum - entries;
  2213. }
  2214. static int dictionary_unittest_walkthrough_stop_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value __maybe_unused, void *data __maybe_unused) {
  2215. return -1;
  2216. }
  2217. static size_t dictionary_unittest_walkthrough_stop(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2218. (void)names;
  2219. (void)values;
  2220. (void)entries;
  2221. int sum = dictionary_walkthrough_read(dict, dictionary_unittest_walkthrough_stop_callback, NULL);
  2222. if(sum != -1) return 1;
  2223. return 0;
  2224. }
  2225. static size_t dictionary_unittest_foreach(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2226. (void)names;
  2227. (void)values;
  2228. (void)entries;
  2229. size_t count = 0;
  2230. char *item;
  2231. dfe_start_read(dict, item)
  2232. count++;
  2233. dfe_done(item);
  2234. if(count > entries) return count - entries;
  2235. return entries - count;
  2236. }
  2237. static size_t dictionary_unittest_foreach_delete_this(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2238. (void)names;
  2239. (void)values;
  2240. (void)entries;
  2241. size_t count = 0;
  2242. char *item;
  2243. dfe_start_write(dict, item)
  2244. if(dictionary_del(dict, item_dfe.name)) count++;
  2245. dfe_done(item);
  2246. if(count > entries) return count - entries;
  2247. return entries - count;
  2248. }
  2249. static size_t dictionary_unittest_destroy(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2250. (void)names;
  2251. (void)values;
  2252. (void)entries;
  2253. size_t bytes = dictionary_destroy(dict);
  2254. fprintf(stderr, " %s() freed %zu bytes,", __FUNCTION__, bytes);
  2255. return 0;
  2256. }
  2257. static usec_t dictionary_unittest_run_and_measure_time(DICTIONARY *dict, char *message, char **names, char **values, size_t entries, size_t *errors, size_t (*callback)(DICTIONARY *dict, char **names, char **values, size_t entries)) {
  2258. fprintf(stderr, "%40s ... ", message);
  2259. usec_t started = now_realtime_usec();
  2260. size_t errs = callback(dict, names, values, entries);
  2261. usec_t ended = now_realtime_usec();
  2262. usec_t dt = ended - started;
  2263. if(callback == dictionary_unittest_destroy) dict = NULL;
  2264. long int found_ok = 0, found_deleted = 0, found_referenced = 0;
  2265. if(dict) {
  2266. DICTIONARY_ITEM *item;
  2267. DOUBLE_LINKED_LIST_FOREACH_FORWARD(dict->items.list, item, prev, next) {
  2268. if(item->refcount >= 0 && !(item ->flags & ITEM_FLAG_DELETED))
  2269. found_ok++;
  2270. else
  2271. found_deleted++;
  2272. if(item->refcount > 0)
  2273. found_referenced++;
  2274. }
  2275. }
  2276. fprintf(stderr, " %zu errors, %d (found %ld) items in dictionary, %d (found %ld) referenced, %d (found %ld) deleted, %"PRIu64" usec \n",
  2277. errs, dict?dict->entries:0, found_ok, dict?dict->referenced_items:0, found_referenced, dict?dict->pending_deletion_items:0, found_deleted, dt);
  2278. *errors += errs;
  2279. return dt;
  2280. }
  2281. static void dictionary_unittest_clone(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2282. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_clone);
  2283. dictionary_unittest_run_and_measure_time(dict, "getting entries", names, values, entries, errors, dictionary_unittest_get_clone);
  2284. dictionary_unittest_run_and_measure_time(dict, "getting non-existing entries", names, values, entries, errors, dictionary_unittest_get_nonexisting);
  2285. dictionary_unittest_run_and_measure_time(dict, "resetting entries", names, values, entries, errors, dictionary_unittest_reset_clone);
  2286. dictionary_unittest_run_and_measure_time(dict, "deleting non-existing entries", names, values, entries, errors, dictionary_unittest_del_nonexisting);
  2287. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  2288. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, errors, dictionary_unittest_walkthrough);
  2289. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, errors, dictionary_unittest_walkthrough_stop);
  2290. dictionary_unittest_run_and_measure_time(dict, "deleting existing entries", names, values, entries, errors, dictionary_unittest_del_existing);
  2291. dictionary_unittest_run_and_measure_time(dict, "walking through empty", names, values, 0, errors, dictionary_unittest_walkthrough);
  2292. dictionary_unittest_run_and_measure_time(dict, "traverse foreach empty", names, values, 0, errors, dictionary_unittest_foreach);
  2293. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, errors, dictionary_unittest_destroy);
  2294. }
  2295. static void dictionary_unittest_nonclone(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2296. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_nonclone);
  2297. dictionary_unittest_run_and_measure_time(dict, "getting entries", names, values, entries, errors, dictionary_unittest_get_nonclone);
  2298. dictionary_unittest_run_and_measure_time(dict, "getting non-existing entries", names, values, entries, errors, dictionary_unittest_get_nonexisting);
  2299. dictionary_unittest_run_and_measure_time(dict, "resetting entries", names, values, entries, errors, dictionary_unittest_reset_nonclone);
  2300. dictionary_unittest_run_and_measure_time(dict, "deleting non-existing entries", names, values, entries, errors, dictionary_unittest_del_nonexisting);
  2301. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  2302. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, errors, dictionary_unittest_walkthrough);
  2303. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, errors, dictionary_unittest_walkthrough_stop);
  2304. dictionary_unittest_run_and_measure_time(dict, "deleting existing entries", names, values, entries, errors, dictionary_unittest_del_existing);
  2305. dictionary_unittest_run_and_measure_time(dict, "walking through empty", names, values, 0, errors, dictionary_unittest_walkthrough);
  2306. dictionary_unittest_run_and_measure_time(dict, "traverse foreach empty", names, values, 0, errors, dictionary_unittest_foreach);
  2307. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, errors, dictionary_unittest_destroy);
  2308. }
  2309. struct dictionary_unittest_sorting {
  2310. const char *old_name;
  2311. const char *old_value;
  2312. size_t count;
  2313. };
  2314. static int dictionary_unittest_sorting_callback(const DICTIONARY_ITEM *item, void *value, void *data) {
  2315. const char *name = dictionary_acquired_item_name((DICTIONARY_ITEM *)item);
  2316. struct dictionary_unittest_sorting *t = (struct dictionary_unittest_sorting *)data;
  2317. const char *v = (const char *)value;
  2318. int ret = 0;
  2319. if(t->old_name && strcmp(t->old_name, name) > 0) {
  2320. fprintf(stderr, "name '%s' should be after '%s'\n", t->old_name, name);
  2321. ret = 1;
  2322. }
  2323. t->count++;
  2324. t->old_name = name;
  2325. t->old_value = v;
  2326. return ret;
  2327. }
  2328. static size_t dictionary_unittest_sorted_walkthrough(DICTIONARY *dict, char **names, char **values, size_t entries) {
  2329. (void)names;
  2330. (void)values;
  2331. struct dictionary_unittest_sorting tmp = { .old_name = NULL, .old_value = NULL, .count = 0 };
  2332. size_t errors;
  2333. errors = dictionary_sorted_walkthrough_read(dict, dictionary_unittest_sorting_callback, &tmp);
  2334. if(tmp.count != entries) {
  2335. fprintf(stderr, "Expected %zu entries, counted %zu\n", entries, tmp.count);
  2336. errors++;
  2337. }
  2338. return errors;
  2339. }
  2340. static void dictionary_unittest_sorting(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2341. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, errors, dictionary_unittest_set_clone);
  2342. dictionary_unittest_run_and_measure_time(dict, "sorted walkthrough", names, values, entries, errors, dictionary_unittest_sorted_walkthrough);
  2343. }
  2344. static void dictionary_unittest_null_dfe(DICTIONARY *dict, char **names, char **values, size_t entries, size_t *errors) {
  2345. dictionary_unittest_run_and_measure_time(dict, "adding null value entries", names, values, entries, errors, dictionary_unittest_set_null);
  2346. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, errors, dictionary_unittest_foreach);
  2347. }
  2348. static int unittest_check_dictionary_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value __maybe_unused, void *data __maybe_unused) {
  2349. return 1;
  2350. }
  2351. static size_t unittest_check_dictionary(const char *label, DICTIONARY *dict, size_t traversable, size_t active_items, size_t deleted_items, size_t referenced_items, size_t pending_deletion) {
  2352. size_t errors = 0;
  2353. size_t ll = 0;
  2354. void *t;
  2355. dfe_start_read(dict, t)
  2356. ll++;
  2357. dfe_done(t);
  2358. fprintf(stderr, "DICT %-20s: dictionary foreach entries %zu, expected %zu...\t\t\t\t\t",
  2359. label, ll, traversable);
  2360. if(ll != traversable) {
  2361. fprintf(stderr, "FAILED\n");
  2362. errors++;
  2363. }
  2364. else
  2365. fprintf(stderr, "OK\n");
  2366. ll = dictionary_walkthrough_read(dict, unittest_check_dictionary_callback, NULL);
  2367. fprintf(stderr, "DICT %-20s: dictionary walkthrough entries %zu, expected %zu...\t\t\t\t",
  2368. label, ll, traversable);
  2369. if(ll != traversable) {
  2370. fprintf(stderr, "FAILED\n");
  2371. errors++;
  2372. }
  2373. else
  2374. fprintf(stderr, "OK\n");
  2375. ll = dictionary_sorted_walkthrough_read(dict, unittest_check_dictionary_callback, NULL);
  2376. fprintf(stderr, "DICT %-20s: dictionary sorted walkthrough entries %zu, expected %zu...\t\t\t",
  2377. label, ll, traversable);
  2378. if(ll != traversable) {
  2379. fprintf(stderr, "FAILED\n");
  2380. errors++;
  2381. }
  2382. else
  2383. fprintf(stderr, "OK\n");
  2384. DICTIONARY_ITEM *item;
  2385. size_t active = 0, deleted = 0, referenced = 0, pending = 0;
  2386. for(item = dict->items.list; item; item = item->next) {
  2387. if(!(item->flags & ITEM_FLAG_DELETED) && !(item->shared->flags & ITEM_FLAG_DELETED))
  2388. active++;
  2389. else {
  2390. deleted++;
  2391. if(item->refcount == 0)
  2392. pending++;
  2393. }
  2394. if(item->refcount > 0)
  2395. referenced++;
  2396. }
  2397. fprintf(stderr, "DICT %-20s: dictionary active items reported %d, counted %zu, expected %zu...\t\t\t",
  2398. label, dict->entries, active, active_items);
  2399. if(active != active_items || active != (size_t)dict->entries) {
  2400. fprintf(stderr, "FAILED\n");
  2401. errors++;
  2402. }
  2403. else
  2404. fprintf(stderr, "OK\n");
  2405. fprintf(stderr, "DICT %-20s: dictionary deleted items counted %zu, expected %zu...\t\t\t\t",
  2406. label, deleted, deleted_items);
  2407. if(deleted != deleted_items) {
  2408. fprintf(stderr, "FAILED\n");
  2409. errors++;
  2410. }
  2411. else
  2412. fprintf(stderr, "OK\n");
  2413. fprintf(stderr, "DICT %-20s: dictionary referenced items reported %d, counted %zu, expected %zu...\t\t",
  2414. label, dict->referenced_items, referenced, referenced_items);
  2415. if(referenced != referenced_items || dict->referenced_items != (long int)referenced) {
  2416. fprintf(stderr, "FAILED\n");
  2417. errors++;
  2418. }
  2419. else
  2420. fprintf(stderr, "OK\n");
  2421. fprintf(stderr, "DICT %-20s: dictionary pending deletion items reported %d, counted %zu, expected %zu...\t",
  2422. label, dict->pending_deletion_items, pending, pending_deletion);
  2423. if(pending != pending_deletion || pending != (size_t)dict->pending_deletion_items) {
  2424. fprintf(stderr, "FAILED\n");
  2425. errors++;
  2426. }
  2427. else
  2428. fprintf(stderr, "OK\n");
  2429. return errors;
  2430. }
  2431. static int check_item_callback(const DICTIONARY_ITEM *item __maybe_unused, void *value, void *data) {
  2432. return value == data;
  2433. }
  2434. static size_t unittest_check_item(const char *label, DICTIONARY *dict,
  2435. DICTIONARY_ITEM *item, const char *name, const char *value, int refcount,
  2436. ITEM_FLAGS deleted_flags, bool searchable, bool browsable, bool linked) {
  2437. size_t errors = 0;
  2438. fprintf(stderr, "ITEM %-20s: name is '%s', expected '%s'...\t\t\t\t\t\t", label, item_get_name(item), name);
  2439. if(strcmp(item_get_name(item), name) != 0) {
  2440. fprintf(stderr, "FAILED\n");
  2441. errors++;
  2442. }
  2443. else
  2444. fprintf(stderr, "OK\n");
  2445. fprintf(stderr, "ITEM %-20s: value is '%s', expected '%s'...\t\t\t\t\t", label, (const char *)item->shared->value, value);
  2446. if(strcmp((const char *)item->shared->value, value) != 0) {
  2447. fprintf(stderr, "FAILED\n");
  2448. errors++;
  2449. }
  2450. else
  2451. fprintf(stderr, "OK\n");
  2452. fprintf(stderr, "ITEM %-20s: refcount is %d, expected %d...\t\t\t\t\t\t\t", label, item->refcount, refcount);
  2453. if (item->refcount != refcount) {
  2454. fprintf(stderr, "FAILED\n");
  2455. errors++;
  2456. }
  2457. else
  2458. fprintf(stderr, "OK\n");
  2459. fprintf(stderr, "ITEM %-20s: deleted flag is %s, expected %s...\t\t\t\t\t", label,
  2460. (item->flags & ITEM_FLAG_DELETED || item->shared->flags & ITEM_FLAG_DELETED)?"true":"false",
  2461. (deleted_flags & ITEM_FLAG_DELETED)?"true":"false");
  2462. if ((item->flags & ITEM_FLAG_DELETED || item->shared->flags & ITEM_FLAG_DELETED) != (deleted_flags & ITEM_FLAG_DELETED)) {
  2463. fprintf(stderr, "FAILED\n");
  2464. errors++;
  2465. }
  2466. else
  2467. fprintf(stderr, "OK\n");
  2468. void *v = dictionary_get(dict, name);
  2469. bool found = v == item->shared->value;
  2470. fprintf(stderr, "ITEM %-20s: searchable %5s, expected %5s...\t\t\t\t\t\t", label,
  2471. found?"true":"false", searchable?"true":"false");
  2472. if(found != searchable) {
  2473. fprintf(stderr, "FAILED\n");
  2474. errors++;
  2475. }
  2476. else
  2477. fprintf(stderr, "OK\n");
  2478. found = false;
  2479. void *t;
  2480. dfe_start_read(dict, t) {
  2481. if(t == item->shared->value) found = true;
  2482. }
  2483. dfe_done(t);
  2484. fprintf(stderr, "ITEM %-20s: dfe browsable %5s, expected %5s...\t\t\t\t\t", label,
  2485. found?"true":"false", browsable?"true":"false");
  2486. if(found != browsable) {
  2487. fprintf(stderr, "FAILED\n");
  2488. errors++;
  2489. }
  2490. else
  2491. fprintf(stderr, "OK\n");
  2492. found = dictionary_walkthrough_read(dict, check_item_callback, item->shared->value);
  2493. fprintf(stderr, "ITEM %-20s: walkthrough browsable %5s, expected %5s...\t\t\t\t", label,
  2494. found?"true":"false", browsable?"true":"false");
  2495. if(found != browsable) {
  2496. fprintf(stderr, "FAILED\n");
  2497. errors++;
  2498. }
  2499. else
  2500. fprintf(stderr, "OK\n");
  2501. found = dictionary_sorted_walkthrough_read(dict, check_item_callback, item->shared->value);
  2502. fprintf(stderr, "ITEM %-20s: sorted walkthrough browsable %5s, expected %5s...\t\t\t", label,
  2503. found?"true":"false", browsable?"true":"false");
  2504. if(found != browsable) {
  2505. fprintf(stderr, "FAILED\n");
  2506. errors++;
  2507. }
  2508. else
  2509. fprintf(stderr, "OK\n");
  2510. found = false;
  2511. DICTIONARY_ITEM *n;
  2512. for(n = dict->items.list; n ;n = n->next)
  2513. if(n == item) found = true;
  2514. fprintf(stderr, "ITEM %-20s: linked %5s, expected %5s...\t\t\t\t\t\t", label,
  2515. found?"true":"false", linked?"true":"false");
  2516. if(found != linked) {
  2517. fprintf(stderr, "FAILED\n");
  2518. errors++;
  2519. }
  2520. else
  2521. fprintf(stderr, "OK\n");
  2522. return errors;
  2523. }
  2524. struct thread_unittest {
  2525. int join;
  2526. DICTIONARY *dict;
  2527. int dups;
  2528. netdata_thread_t thread;
  2529. struct dictionary_stats stats;
  2530. };
  2531. static void *unittest_dict_thread(void *arg) {
  2532. struct thread_unittest *tu = arg;
  2533. for(; 1 ;) {
  2534. if(__atomic_load_n(&tu->join, __ATOMIC_RELAXED))
  2535. break;
  2536. DICT_ITEM_CONST DICTIONARY_ITEM *item =
  2537. dictionary_set_and_acquire_item_advanced(tu->dict, "dict thread checking 1234567890",
  2538. -1, NULL, 0, NULL);
  2539. tu->stats.ops.inserts++;
  2540. dictionary_get(tu->dict, dictionary_acquired_item_name(item));
  2541. tu->stats.ops.searches++;
  2542. void *t1;
  2543. dfe_start_write(tu->dict, t1) {
  2544. // this should delete the referenced item
  2545. dictionary_del(tu->dict, t1_dfe.name);
  2546. tu->stats.ops.deletes++;
  2547. void *t2;
  2548. dfe_start_write(tu->dict, t2) {
  2549. // this should add another
  2550. dictionary_set(tu->dict, t2_dfe.name, NULL, 0);
  2551. tu->stats.ops.inserts++;
  2552. dictionary_get(tu->dict, dictionary_acquired_item_name(item));
  2553. tu->stats.ops.searches++;
  2554. // and this should delete it again
  2555. dictionary_del(tu->dict, t2_dfe.name);
  2556. tu->stats.ops.deletes++;
  2557. }
  2558. dfe_done(t2);
  2559. tu->stats.ops.traversals++;
  2560. // this should fail to add it
  2561. dictionary_set(tu->dict, t1_dfe.name, NULL, 0);
  2562. tu->stats.ops.inserts++;
  2563. dictionary_del(tu->dict, t1_dfe.name);
  2564. tu->stats.ops.deletes++;
  2565. }
  2566. dfe_done(t1);
  2567. tu->stats.ops.traversals++;
  2568. for(int i = 0; i < tu->dups ; i++) {
  2569. dictionary_acquired_item_dup(tu->dict, item);
  2570. dictionary_get(tu->dict, dictionary_acquired_item_name(item));
  2571. tu->stats.ops.searches++;
  2572. }
  2573. for(int i = 0; i < tu->dups ; i++) {
  2574. dictionary_acquired_item_release(tu->dict, item);
  2575. dictionary_del(tu->dict, dictionary_acquired_item_name(item));
  2576. tu->stats.ops.deletes++;
  2577. }
  2578. dictionary_acquired_item_release(tu->dict, item);
  2579. dictionary_del(tu->dict, "dict thread checking 1234567890");
  2580. tu->stats.ops.deletes++;
  2581. // test concurrent deletions and flushes
  2582. {
  2583. if(gettid() % 2) {
  2584. char buf [256 + 1];
  2585. for (int i = 0; i < 1000; i++) {
  2586. snprintfz(buf, sizeof(buf) - 1, "del/flush test %d", i);
  2587. dictionary_set(tu->dict, buf, NULL, 0);
  2588. tu->stats.ops.inserts++;
  2589. }
  2590. for (int i = 0; i < 1000; i++) {
  2591. snprintfz(buf, sizeof(buf) - 1, "del/flush test %d", i);
  2592. dictionary_del(tu->dict, buf);
  2593. tu->stats.ops.deletes++;
  2594. }
  2595. }
  2596. else {
  2597. for (int i = 0; i < 10; i++) {
  2598. dictionary_flush(tu->dict);
  2599. tu->stats.ops.flushes++;
  2600. }
  2601. }
  2602. }
  2603. }
  2604. return arg;
  2605. }
  2606. static int dictionary_unittest_threads() {
  2607. time_t seconds_to_run = 5;
  2608. int threads_to_create = 2;
  2609. struct thread_unittest tu[threads_to_create];
  2610. memset(tu, 0, sizeof(struct thread_unittest) * threads_to_create);
  2611. fprintf(
  2612. stderr,
  2613. "\nChecking dictionary concurrency with %d threads for %lld seconds...\n",
  2614. threads_to_create,
  2615. (long long)seconds_to_run);
  2616. // threads testing of dictionary
  2617. struct dictionary_stats stats = {};
  2618. tu[0].join = 0;
  2619. tu[0].dups = 1;
  2620. tu[0].dict = dictionary_create_advanced(DICT_OPTION_DONT_OVERWRITE_VALUE, &stats, 0);
  2621. for (int i = 0; i < threads_to_create; i++) {
  2622. if(i)
  2623. tu[i] = tu[0];
  2624. char buf[100 + 1];
  2625. snprintf(buf, 100, "dict%d", i);
  2626. netdata_thread_create(
  2627. &tu[i].thread,
  2628. buf,
  2629. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  2630. unittest_dict_thread,
  2631. &tu[i]);
  2632. }
  2633. sleep_usec(seconds_to_run * USEC_PER_SEC);
  2634. for (int i = 0; i < threads_to_create; i++) {
  2635. __atomic_store_n(&tu[i].join, 1, __ATOMIC_RELAXED);
  2636. void *retval;
  2637. netdata_thread_join(tu[i].thread, &retval);
  2638. if(i) {
  2639. tu[0].stats.ops.inserts += tu[i].stats.ops.inserts;
  2640. tu[0].stats.ops.deletes += tu[i].stats.ops.deletes;
  2641. tu[0].stats.ops.searches += tu[i].stats.ops.searches;
  2642. tu[0].stats.ops.flushes += tu[i].stats.ops.flushes;
  2643. tu[0].stats.ops.traversals += tu[i].stats.ops.traversals;
  2644. }
  2645. }
  2646. fprintf(stderr,
  2647. "CALLS : inserts %zu"
  2648. ", deletes %zu"
  2649. ", searches %zu"
  2650. ", traversals %zu"
  2651. ", flushes %zu"
  2652. "\n",
  2653. tu[0].stats.ops.inserts,
  2654. tu[0].stats.ops.deletes,
  2655. tu[0].stats.ops.searches,
  2656. tu[0].stats.ops.traversals,
  2657. tu[0].stats.ops.flushes
  2658. );
  2659. #ifdef DICT_WITH_STATS
  2660. fprintf(stderr,
  2661. "ACTUAL: inserts %zu"
  2662. ", deletes %zu"
  2663. ", searches %zu"
  2664. ", traversals %zu"
  2665. ", resets %zu"
  2666. ", flushes %zu"
  2667. ", entries %d"
  2668. ", referenced_items %d"
  2669. ", pending deletions %d"
  2670. ", check spins %zu"
  2671. ", insert spins %zu"
  2672. ", delete spins %zu"
  2673. ", search ignores %zu"
  2674. "\n",
  2675. stats.ops.inserts,
  2676. stats.ops.deletes,
  2677. stats.ops.searches,
  2678. stats.ops.traversals,
  2679. stats.ops.resets,
  2680. stats.ops.flushes,
  2681. tu[0].dict->entries,
  2682. tu[0].dict->referenced_items,
  2683. tu[0].dict->pending_deletion_items,
  2684. stats.spin_locks.use_spins,
  2685. stats.spin_locks.insert_spins,
  2686. stats.spin_locks.delete_spins,
  2687. stats.spin_locks.search_spins
  2688. );
  2689. #endif
  2690. dictionary_destroy(tu[0].dict);
  2691. return 0;
  2692. }
  2693. struct thread_view_unittest {
  2694. int join;
  2695. DICTIONARY *master;
  2696. DICTIONARY *view;
  2697. DICTIONARY_ITEM *item_master;
  2698. int dups;
  2699. };
  2700. static void *unittest_dict_master_thread(void *arg) {
  2701. struct thread_view_unittest *tv = arg;
  2702. DICTIONARY_ITEM *item = NULL;
  2703. int loops = 0;
  2704. while(!__atomic_load_n(&tv->join, __ATOMIC_RELAXED)) {
  2705. if(!item)
  2706. item = dictionary_set_and_acquire_item(tv->master, "ITEM1", "123", strlen("123") + 1);
  2707. if(__atomic_load_n(&tv->item_master, __ATOMIC_RELAXED) != NULL) {
  2708. dictionary_acquired_item_release(tv->master, item);
  2709. dictionary_del(tv->master, "ITEM1");
  2710. item = NULL;
  2711. loops++;
  2712. continue;
  2713. }
  2714. dictionary_acquired_item_dup(tv->master, item); // for the view thread
  2715. __atomic_store_n(&tv->item_master, item, __ATOMIC_RELAXED);
  2716. dictionary_del(tv->master, "ITEM1");
  2717. for(int i = 0; i < tv->dups + loops ; i++) {
  2718. dictionary_acquired_item_dup(tv->master, item);
  2719. }
  2720. for(int i = 0; i < tv->dups + loops ; i++) {
  2721. dictionary_acquired_item_release(tv->master, item);
  2722. }
  2723. dictionary_acquired_item_release(tv->master, item);
  2724. item = NULL;
  2725. loops = 0;
  2726. }
  2727. return arg;
  2728. }
  2729. static void *unittest_dict_view_thread(void *arg) {
  2730. struct thread_view_unittest *tv = arg;
  2731. DICTIONARY_ITEM *m_item = NULL;
  2732. while(!__atomic_load_n(&tv->join, __ATOMIC_RELAXED)) {
  2733. if(!(m_item = __atomic_load_n(&tv->item_master, __ATOMIC_RELAXED)))
  2734. continue;
  2735. DICTIONARY_ITEM *v_item = dictionary_view_set_and_acquire_item(tv->view, "ITEM2", m_item);
  2736. dictionary_acquired_item_release(tv->master, m_item);
  2737. __atomic_store_n(&tv->item_master, NULL, __ATOMIC_RELAXED);
  2738. for(int i = 0; i < tv->dups ; i++) {
  2739. dictionary_acquired_item_dup(tv->view, v_item);
  2740. }
  2741. for(int i = 0; i < tv->dups ; i++) {
  2742. dictionary_acquired_item_release(tv->view, v_item);
  2743. }
  2744. dictionary_del(tv->view, "ITEM2");
  2745. while(!__atomic_load_n(&tv->join, __ATOMIC_RELAXED) && !(m_item = __atomic_load_n(&tv->item_master, __ATOMIC_RELAXED))) {
  2746. dictionary_acquired_item_dup(tv->view, v_item);
  2747. dictionary_acquired_item_release(tv->view, v_item);
  2748. }
  2749. dictionary_acquired_item_release(tv->view, v_item);
  2750. }
  2751. return arg;
  2752. }
  2753. static int dictionary_unittest_view_threads() {
  2754. struct thread_view_unittest tv = {
  2755. .join = 0,
  2756. .master = NULL,
  2757. .view = NULL,
  2758. .item_master = NULL,
  2759. .dups = 1,
  2760. };
  2761. // threads testing of dictionary
  2762. struct dictionary_stats stats_master = {};
  2763. struct dictionary_stats stats_view = {};
  2764. tv.master = dictionary_create_advanced(DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE, &stats_master, 0);
  2765. tv.view = dictionary_create_view(tv.master);
  2766. tv.view->stats = &stats_view;
  2767. time_t seconds_to_run = 5;
  2768. fprintf(
  2769. stderr,
  2770. "\nChecking dictionary concurrency with 1 master and 1 view threads for %lld seconds...\n",
  2771. (long long)seconds_to_run);
  2772. netdata_thread_t master_thread, view_thread;
  2773. tv.join = 0;
  2774. netdata_thread_create(
  2775. &master_thread,
  2776. "master",
  2777. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  2778. unittest_dict_master_thread,
  2779. &tv);
  2780. netdata_thread_create(
  2781. &view_thread,
  2782. "view",
  2783. NETDATA_THREAD_OPTION_DONT_LOG | NETDATA_THREAD_OPTION_JOINABLE,
  2784. unittest_dict_view_thread,
  2785. &tv);
  2786. sleep_usec(seconds_to_run * USEC_PER_SEC);
  2787. __atomic_store_n(&tv.join, 1, __ATOMIC_RELAXED);
  2788. void *retval;
  2789. netdata_thread_join(view_thread, &retval);
  2790. netdata_thread_join(master_thread, &retval);
  2791. #ifdef DICT_WITH_STATS
  2792. fprintf(stderr,
  2793. "MASTER: inserts %zu"
  2794. ", deletes %zu"
  2795. ", searches %zu"
  2796. ", resets %zu"
  2797. ", entries %d"
  2798. ", referenced_items %d"
  2799. ", pending deletions %d"
  2800. ", check spins %zu"
  2801. ", insert spins %zu"
  2802. ", delete spins %zu"
  2803. ", search ignores %zu"
  2804. "\n",
  2805. stats_master.ops.inserts,
  2806. stats_master.ops.deletes,
  2807. stats_master.ops.searches,
  2808. stats_master.ops.resets,
  2809. tv.master->entries,
  2810. tv.master->referenced_items,
  2811. tv.master->pending_deletion_items,
  2812. stats_master.spin_locks.use_spins,
  2813. stats_master.spin_locks.insert_spins,
  2814. stats_master.spin_locks.delete_spins,
  2815. stats_master.spin_locks.search_spins
  2816. );
  2817. fprintf(stderr,
  2818. "VIEW : inserts %zu"
  2819. ", deletes %zu"
  2820. ", searches %zu"
  2821. ", resets %zu"
  2822. ", entries %d"
  2823. ", referenced_items %d"
  2824. ", pending deletions %d"
  2825. ", check spins %zu"
  2826. ", insert spins %zu"
  2827. ", delete spins %zu"
  2828. ", search ignores %zu"
  2829. "\n",
  2830. stats_view.ops.inserts,
  2831. stats_view.ops.deletes,
  2832. stats_view.ops.searches,
  2833. stats_view.ops.resets,
  2834. tv.view->entries,
  2835. tv.view->referenced_items,
  2836. tv.view->pending_deletion_items,
  2837. stats_view.spin_locks.use_spins,
  2838. stats_view.spin_locks.insert_spins,
  2839. stats_view.spin_locks.delete_spins,
  2840. stats_view.spin_locks.search_spins
  2841. );
  2842. #endif
  2843. dictionary_destroy(tv.master);
  2844. dictionary_destroy(tv.view);
  2845. return 0;
  2846. }
  2847. size_t dictionary_unittest_views(void) {
  2848. size_t errors = 0;
  2849. struct dictionary_stats stats = {};
  2850. DICTIONARY *master = dictionary_create_advanced(DICT_OPTION_NONE, &stats, 0);
  2851. DICTIONARY *view = dictionary_create_view(master);
  2852. fprintf(stderr, "\n\nChecking dictionary views...\n");
  2853. // Add an item to both master and view, then remove the view first and the master second
  2854. fprintf(stderr, "\nPASS 1: Adding 1 item to master:\n");
  2855. DICTIONARY_ITEM *item1_on_master = dictionary_set_and_acquire_item(master, "KEY 1", "VALUE1", strlen("VALUE1") + 1);
  2856. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2857. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2858. fprintf(stderr, "\nPASS 1: Adding master item to view:\n");
  2859. DICTIONARY_ITEM *item1_on_view = dictionary_view_set_and_acquire_item(view, "KEY 1 ON VIEW", item1_on_master);
  2860. errors += unittest_check_dictionary("view", view, 1, 1, 0, 1, 0);
  2861. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2862. fprintf(stderr, "\nPASS 1: Deleting view item:\n");
  2863. dictionary_del(view, "KEY 1 ON VIEW");
  2864. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2865. errors += unittest_check_dictionary("view", view, 0, 0, 1, 1, 0);
  2866. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2867. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2868. fprintf(stderr, "\nPASS 1: Releasing the deleted view item:\n");
  2869. dictionary_acquired_item_release(view, item1_on_view);
  2870. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2871. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2872. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2873. fprintf(stderr, "\nPASS 1: Releasing the acquired master item:\n");
  2874. dictionary_acquired_item_release(master, item1_on_master);
  2875. errors += unittest_check_dictionary("master", master, 1, 1, 0, 0, 0);
  2876. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2877. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 0, ITEM_FLAG_NONE, true, true, true);
  2878. fprintf(stderr, "\nPASS 1: Deleting the released master item:\n");
  2879. dictionary_del(master, "KEY 1");
  2880. errors += unittest_check_dictionary("master", master, 0, 0, 0, 0, 0);
  2881. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2882. // The other way now:
  2883. // Add an item to both master and view, then remove the master first and verify it is deleted on the view also
  2884. fprintf(stderr, "\nPASS 2: Adding 1 item to master:\n");
  2885. item1_on_master = dictionary_set_and_acquire_item(master, "KEY 1", "VALUE1", strlen("VALUE1") + 1);
  2886. errors += unittest_check_dictionary("master", master, 1, 1, 0, 1, 0);
  2887. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2888. fprintf(stderr, "\nPASS 2: Adding master item to view:\n");
  2889. item1_on_view = dictionary_view_set_and_acquire_item(view, "KEY 1 ON VIEW", item1_on_master);
  2890. errors += unittest_check_dictionary("view", view, 1, 1, 0, 1, 0);
  2891. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_NONE, true, true, true);
  2892. fprintf(stderr, "\nPASS 2: Deleting master item:\n");
  2893. dictionary_del(master, "KEY 1");
  2894. garbage_collect_pending_deletes(view);
  2895. errors += unittest_check_dictionary("master", master, 0, 0, 1, 1, 0);
  2896. errors += unittest_check_dictionary("view", view, 0, 0, 1, 1, 0);
  2897. errors += unittest_check_item("master", master, item1_on_master, "KEY 1", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2898. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2899. fprintf(stderr, "\nPASS 2: Releasing the acquired master item:\n");
  2900. dictionary_acquired_item_release(master, item1_on_master);
  2901. errors += unittest_check_dictionary("master", master, 0, 0, 1, 0, 1);
  2902. errors += unittest_check_dictionary("view", view, 0, 0, 1, 1, 0);
  2903. errors += unittest_check_item("view", view, item1_on_view, "KEY 1 ON VIEW", item1_on_master->shared->value, 1, ITEM_FLAG_DELETED, false, false, true);
  2904. fprintf(stderr, "\nPASS 2: Releasing the deleted view item:\n");
  2905. dictionary_acquired_item_release(view, item1_on_view);
  2906. errors += unittest_check_dictionary("master", master, 0, 0, 1, 0, 1);
  2907. errors += unittest_check_dictionary("view", view, 0, 0, 1, 0, 1);
  2908. dictionary_destroy(master);
  2909. dictionary_destroy(view);
  2910. return errors;
  2911. }
  2912. int dictionary_unittest(size_t entries) {
  2913. if(entries < 10) entries = 10;
  2914. DICTIONARY *dict;
  2915. size_t errors = 0;
  2916. fprintf(stderr, "Generating %zu names and values...\n", entries);
  2917. char **names = dictionary_unittest_generate_names(entries);
  2918. char **values = dictionary_unittest_generate_values(entries);
  2919. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  2920. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED);
  2921. dictionary_unittest_clone(dict, names, values, entries, &errors);
  2922. fprintf(stderr, "\nCreating dictionary multi threaded, clone, %zu items\n", entries);
  2923. dict = dictionary_create(DICT_OPTION_NONE);
  2924. dictionary_unittest_clone(dict, names, values, entries, &errors);
  2925. fprintf(stderr, "\nCreating dictionary single threaded, non-clone, add-in-front options, %zu items\n", entries);
  2926. dict = dictionary_create(
  2927. DICT_OPTION_SINGLE_THREADED | DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE |
  2928. DICT_OPTION_ADD_IN_FRONT);
  2929. dictionary_unittest_nonclone(dict, names, values, entries, &errors);
  2930. fprintf(stderr, "\nCreating dictionary multi threaded, non-clone, add-in-front options, %zu items\n", entries);
  2931. dict = dictionary_create(
  2932. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_ADD_IN_FRONT);
  2933. dictionary_unittest_nonclone(dict, names, values, entries, &errors);
  2934. fprintf(stderr, "\nCreating dictionary single-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  2935. dict = dictionary_create(
  2936. DICT_OPTION_SINGLE_THREADED | DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE |
  2937. DICT_OPTION_DONT_OVERWRITE_VALUE);
  2938. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  2939. dictionary_unittest_run_and_measure_time(dict, "resetting non-overwrite entries", names, values, entries, &errors, dictionary_unittest_reset_dont_overwrite_nonclone);
  2940. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop", names, values, entries, &errors, dictionary_unittest_foreach);
  2941. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback", names, values, entries, &errors, dictionary_unittest_walkthrough);
  2942. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback stop", names, values, entries, &errors, dictionary_unittest_walkthrough_stop);
  2943. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2944. fprintf(stderr, "\nCreating dictionary multi-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  2945. dict = dictionary_create(
  2946. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE);
  2947. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  2948. dictionary_unittest_run_and_measure_time(dict, "walkthrough write delete this", names, values, entries, &errors, dictionary_unittest_walkthrough_delete_this);
  2949. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2950. fprintf(stderr, "\nCreating dictionary multi-threaded, non-clone, don't overwrite options, %zu items\n", entries);
  2951. dict = dictionary_create(
  2952. DICT_OPTION_NAME_LINK_DONT_CLONE | DICT_OPTION_VALUE_LINK_DONT_CLONE | DICT_OPTION_DONT_OVERWRITE_VALUE);
  2953. dictionary_unittest_run_and_measure_time(dict, "adding entries", names, values, entries, &errors, dictionary_unittest_set_nonclone);
  2954. dictionary_unittest_run_and_measure_time(dict, "foreach write delete this", names, values, entries, &errors, dictionary_unittest_foreach_delete_this);
  2955. dictionary_unittest_run_and_measure_time(dict, "traverse foreach read loop empty", names, values, 0, &errors, dictionary_unittest_foreach);
  2956. dictionary_unittest_run_and_measure_time(dict, "walkthrough read callback empty", names, values, 0, &errors, dictionary_unittest_walkthrough);
  2957. dictionary_unittest_run_and_measure_time(dict, "destroying empty dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2958. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  2959. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED);
  2960. dictionary_unittest_sorting(dict, names, values, entries, &errors);
  2961. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2962. fprintf(stderr, "\nCreating dictionary single threaded, clone, %zu items\n", entries);
  2963. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED);
  2964. dictionary_unittest_null_dfe(dict, names, values, entries, &errors);
  2965. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2966. fprintf(stderr, "\nCreating dictionary single threaded, noclone, %zu items\n", entries);
  2967. dict = dictionary_create(DICT_OPTION_SINGLE_THREADED | DICT_OPTION_VALUE_LINK_DONT_CLONE);
  2968. dictionary_unittest_null_dfe(dict, names, values, entries, &errors);
  2969. dictionary_unittest_run_and_measure_time(dict, "destroying full dictionary", names, values, entries, &errors, dictionary_unittest_destroy);
  2970. // check reference counters
  2971. {
  2972. fprintf(stderr, "\nTesting reference counters:\n");
  2973. dict = dictionary_create(DICT_OPTION_NONE | DICT_OPTION_NAME_LINK_DONT_CLONE);
  2974. errors += unittest_check_dictionary("", dict, 0, 0, 0, 0, 0);
  2975. fprintf(stderr, "\nAdding test item to dictionary and acquiring it\n");
  2976. dictionary_set(dict, "test", "ITEM1", 6);
  2977. DICTIONARY_ITEM *item = (DICTIONARY_ITEM *)dictionary_get_and_acquire_item(dict, "test");
  2978. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  2979. errors += unittest_check_item("ACQUIRED", dict, item, "test", "ITEM1", 1, ITEM_FLAG_NONE, true, true, true);
  2980. fprintf(stderr, "\nChecking that reference counters are increased:\n");
  2981. void *t;
  2982. dfe_start_read(dict, t) {
  2983. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  2984. errors += unittest_check_item("ACQUIRED TRAVERSAL", dict, item, "test", "ITEM1", 2, ITEM_FLAG_NONE, true, true, true);
  2985. }
  2986. dfe_done(t);
  2987. fprintf(stderr, "\nChecking that reference counters are decreased:\n");
  2988. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  2989. errors += unittest_check_item("ACQUIRED TRAVERSAL 2", dict, item, "test", "ITEM1", 1, ITEM_FLAG_NONE, true, true, true);
  2990. fprintf(stderr, "\nDeleting the item we have acquired:\n");
  2991. dictionary_del(dict, "test");
  2992. errors += unittest_check_dictionary("", dict, 0, 0, 1, 1, 0);
  2993. errors += unittest_check_item("DELETED", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  2994. fprintf(stderr, "\nAdding another item with the same name of the item we deleted, while being acquired:\n");
  2995. dictionary_set(dict, "test", "ITEM2", 6);
  2996. errors += unittest_check_dictionary("", dict, 1, 1, 1, 1, 0);
  2997. fprintf(stderr, "\nAcquiring the second item:\n");
  2998. DICTIONARY_ITEM *item2 = (DICTIONARY_ITEM *)dictionary_get_and_acquire_item(dict, "test");
  2999. errors += unittest_check_item("FIRST", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  3000. errors += unittest_check_item("SECOND", dict, item2, "test", "ITEM2", 1, ITEM_FLAG_NONE, true, true, true);
  3001. errors += unittest_check_dictionary("", dict, 1, 1, 1, 2, 0);
  3002. fprintf(stderr, "\nReleasing the second item (the first is still acquired):\n");
  3003. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)item2);
  3004. errors += unittest_check_dictionary("", dict, 1, 1, 1, 1, 0);
  3005. errors += unittest_check_item("FIRST", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  3006. errors += unittest_check_item("SECOND RELEASED", dict, item2, "test", "ITEM2", 0, ITEM_FLAG_NONE, true, true, true);
  3007. fprintf(stderr, "\nDeleting the second item (the first is still acquired):\n");
  3008. dictionary_del(dict, "test");
  3009. errors += unittest_check_dictionary("", dict, 0, 0, 1, 1, 0);
  3010. errors += unittest_check_item("ACQUIRED DELETED", dict, item, "test", "ITEM1", 1, ITEM_FLAG_DELETED, false, false, true);
  3011. fprintf(stderr, "\nReleasing the first item (which we have already deleted):\n");
  3012. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)item);
  3013. dfe_start_write(dict, item) ; dfe_done(item);
  3014. errors += unittest_check_dictionary("", dict, 0, 0, 1, 0, 1);
  3015. fprintf(stderr, "\nAdding again the test item to dictionary and acquiring it\n");
  3016. dictionary_set(dict, "test", "ITEM1", 6);
  3017. item = (DICTIONARY_ITEM *)dictionary_get_and_acquire_item(dict, "test");
  3018. errors += unittest_check_dictionary("", dict, 1, 1, 0, 1, 0);
  3019. errors += unittest_check_item("RE-ADDITION", dict, item, "test", "ITEM1", 1, ITEM_FLAG_NONE, true, true, true);
  3020. fprintf(stderr, "\nDestroying the dictionary while we have acquired an item\n");
  3021. dictionary_destroy(dict);
  3022. fprintf(stderr, "Releasing the item (on a destroyed dictionary)\n");
  3023. dictionary_acquired_item_release(dict, (DICTIONARY_ITEM *)item);
  3024. item = NULL;
  3025. dict = NULL;
  3026. }
  3027. dictionary_unittest_free_char_pp(names, entries);
  3028. dictionary_unittest_free_char_pp(values, entries);
  3029. errors += dictionary_unittest_views();
  3030. errors += dictionary_unittest_threads();
  3031. errors += dictionary_unittest_view_threads();
  3032. fprintf(stderr, "\n%zu errors found\n", errors);
  3033. return errors ? 1 : 0;
  3034. }