mf_keycache.cc 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688
  1. /* Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
  2. This program is free software; you can redistribute it and/or modify
  3. it under the terms of the GNU General Public License, version 2.0,
  4. as published by the Free Software Foundation.
  5. This program is also distributed with certain software (including
  6. but not limited to OpenSSL) that is licensed under separate terms,
  7. as designated in a particular file or component or in included license
  8. documentation. The authors of MySQL hereby grant you an additional
  9. permission to link the program and your derivative works with the
  10. separately licensed software that they have included with MySQL.
  11. Without limiting anything contained in the foregoing, this file,
  12. which is part of C Driver for MySQL (Connector/C), is also subject to the
  13. Universal FOSS Exception, version 1.0, a copy of which can be found at
  14. http://oss.oracle.com/licenses/universal-foss-exception.
  15. This program is distributed in the hope that it will be useful,
  16. but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. GNU General Public License, version 2.0, for more details.
  19. You should have received a copy of the GNU General Public License
  20. along with this program; if not, write to the Free Software
  21. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
  22. /**
  23. @file mysys/mf_keycache.cc
  24. These functions handle keyblock caching for ISAM and MyISAM tables.
  25. One cache can handle many files.
  26. It must contain buffers of the same blocksize.
  27. init_key_cache() should be used to init cache handler.
  28. The free list (free_block_list) is a stack like structure.
  29. When a block is freed by free_block(), it is pushed onto the stack.
  30. When a new block is required it is first tried to pop one from the stack.
  31. If the stack is empty, it is tried to get a never-used block from the pool.
  32. If this is empty too, then a block is taken from the LRU ring, flushing it
  33. to disk, if neccessary. This is handled in find_key_block().
  34. With the new free list, the blocks can have three temperatures:
  35. hot, warm and cold (which is free). This is remembered in the block header
  36. by the enum BLOCK_TEMPERATURE temperature variable. Remembering the
  37. temperature is neccessary to correctly count the number of warm blocks,
  38. which is required to decide when blocks are allowed to become hot. Whenever
  39. a block is inserted to another (sub-)chain, we take the old and new
  40. temperature into account to decide if we got one more or less warm block.
  41. blocks_unused is the sum of never used blocks in the pool and of currently
  42. free blocks. blocks_used is the number of blocks fetched from the pool and
  43. as such gives the maximum number of in-use blocks at any time.
  44. */
  45. /*
  46. Key Cache Locking
  47. =================
  48. All key cache locking is done with a single mutex per key cache:
  49. keycache->cache_lock. This mutex is locked almost all the time
  50. when executing code in this file (mf_keycache.c).
  51. However it is released for I/O and some copy operations.
  52. The cache_lock is also released when waiting for some event. Waiting
  53. and signalling is done via condition variables. In most cases the
  54. thread waits on its thread->suspend condition variable. Every thread
  55. has a my_thread_var structure, which contains this variable and a
  56. '*next' and '**prev' pointer. These pointers are used to insert the
  57. thread into a wait queue.
  58. A thread can wait for one block and thus be in one wait queue at a
  59. time only.
  60. Before starting to wait on its condition variable with
  61. mysql_cond_wait(), the thread enters itself to a specific wait queue
  62. with link_into_queue() (double linked with '*next' + '**prev') or
  63. wait_on_queue() (single linked with '*next').
  64. Another thread, when releasing a resource, looks up the waiting thread
  65. in the related wait queue. It sends a signal with
  66. mysql_cond_signal() to the waiting thread.
  67. NOTE: Depending on the particular wait situation, either the sending
  68. thread removes the waiting thread from the wait queue with
  69. unlink_from_queue() or release_whole_queue() respectively, or the waiting
  70. thread removes itself.
  71. There is one exception from this locking scheme when one thread wants
  72. to reuse a block for some other address. This works by first marking
  73. the block reserved (status= BLOCK_IN_SWITCH) and then waiting for all
  74. threads that are reading the block to finish. Each block has a
  75. reference to a condition variable (condvar). It holds a reference to
  76. the thread->suspend condition variable for the waiting thread (if such
  77. a thread exists). When that thread is signaled, the reference is
  78. cleared. The number of readers of a block is registered in
  79. block->hash_link->requests. See wait_for_readers() / remove_reader()
  80. for details. This is similar to the above, but it clearly means that
  81. only one thread can wait for a particular block. There is no queue in
  82. this case. Strangely enough block->convar is used for waiting for the
  83. assigned hash_link only. More precisely it is used to wait for all
  84. requests to be unregistered from the assigned hash_link.
  85. The resize_queue serves two purposes:
  86. 1. Threads that want to do a resize wait there if in_resize is set.
  87. This is not used in the server. The server refuses a second resize
  88. request if one is already active. keycache->in_init is used for the
  89. synchronization. See set_var.cc.
  90. 2. Threads that want to access blocks during resize wait here during
  91. the re-initialization phase.
  92. When the resize is done, all threads on the queue are signalled.
  93. Hypothetical resizers can compete for resizing, and read/write
  94. requests will restart to request blocks from the freshly resized
  95. cache. If the cache has been resized too small, it is disabled and
  96. 'can_be_used' is false. In this case read/write requests bypass the
  97. cache. Since they increment and decrement 'cnt_for_resize_op', the
  98. next resizer can wait on the queue 'waiting_for_resize_cnt' until all
  99. I/O finished.
  100. */
  101. #include <errno.h>
  102. #include <stddef.h>
  103. #include <string.h>
  104. #include <sys/types.h>
  105. #include <algorithm>
  106. #include "keycache.h"
  107. #include "my_bit.h"
  108. #include "my_compiler.h"
  109. #include "my_dbug.h"
  110. #include "my_inttypes.h"
  111. #include "my_io.h"
  112. #include "my_loglevel.h"
  113. #include "my_macros.h"
  114. #include "my_pointer_arithmetic.h"
  115. #include "my_sys.h"
  116. #include "my_thread_local.h"
  117. #include "mysql/psi/mysql_cond.h"
  118. #include "mysql/psi/mysql_mutex.h"
  119. #include "mysql/service_mysql_alloc.h"
  120. #include "mysys/mysys_priv.h"
  121. #include "mysys_err.h"
  122. #include "template_utils.h"
  123. #include "thr_mutex.h"
  124. #define STRUCT_PTR(TYPE, MEMBER, a) (TYPE *)((char *)(a)-offsetof(TYPE, MEMBER))
  125. /* types of condition variables */
  126. #define COND_FOR_REQUESTED 0
  127. #define COND_FOR_SAVED 1
  128. typedef mysql_cond_t KEYCACHE_CONDVAR;
  129. /* descriptor of the page in the key cache block buffer */
  130. struct KEYCACHE_PAGE {
  131. int file; /* file to which the page belongs to */
  132. my_off_t filepos; /* position of the page in the file */
  133. };
  134. /* element in the chain of a hash table bucket */
  135. struct HASH_LINK {
  136. HASH_LINK *next, **prev; /* to connect links in the same bucket */
  137. BLOCK_LINK *block; /* reference to the block for the page: */
  138. File file; /* from such a file */
  139. my_off_t diskpos; /* with such an offset */
  140. uint requests; /* number of requests for the page */
  141. };
  142. /* simple states of a block */
  143. #define BLOCK_ERROR 1 /* an error occurred when performing file i/o */
  144. #define BLOCK_READ 2 /* file block is in the block buffer */
  145. #define BLOCK_IN_SWITCH 4 /* block is preparing to read new page */
  146. #define BLOCK_REASSIGNED 8 /* blk does not accept requests for old page */
  147. #define BLOCK_IN_FLUSH 16 /* block is selected for flush */
  148. #define BLOCK_CHANGED 32 /* block buffer contains a dirty page */
  149. #define BLOCK_IN_USE 64 /* block is not free */
  150. #define BLOCK_IN_EVICTION 128 /* block is selected for eviction */
  151. #define BLOCK_IN_FLUSHWRITE 256 /* block is in write to file */
  152. #define BLOCK_FOR_UPDATE 512 /* block is selected for buffer modification */
  153. /* page status, returned by find_key_block */
  154. #define PAGE_READ 0
  155. #define PAGE_TO_BE_READ 1
  156. #define PAGE_WAIT_TO_BE_READ 2
  157. /* block temperature determines in which (sub-)chain the block currently is */
  158. enum BLOCK_TEMPERATURE { BLOCK_COLD /*free*/, BLOCK_WARM, BLOCK_HOT };
  159. /* key cache block */
  160. struct BLOCK_LINK {
  161. BLOCK_LINK
  162. *next_used, **prev_used; /* to connect links in the LRU chain (ring) */
  163. BLOCK_LINK
  164. *next_changed, **prev_changed; /* for lists of file dirty/clean blocks */
  165. HASH_LINK *hash_link; /* backward ptr to referring hash_link */
  166. KEYCACHE_WQUEUE wqueue[2]; /* queues on waiting requests for new/old pages */
  167. uint requests; /* number of requests for the block */
  168. uchar *buffer; /* buffer for the block page */
  169. uint offset; /* beginning of modified data in the buffer */
  170. uint length; /* end of data in the buffer */
  171. uint status; /* state of the block */
  172. enum BLOCK_TEMPERATURE temperature; /* block temperature: cold, warm, hot */
  173. uint hits_left; /* number of hits left until promotion */
  174. ulonglong last_hit_time; /* timestamp of the last hit */
  175. KEYCACHE_CONDVAR *condvar; /* condition variable for 'no readers' event */
  176. };
  177. KEY_CACHE dflt_key_cache_var;
  178. KEY_CACHE *dflt_key_cache = &dflt_key_cache_var;
  179. #define FLUSH_CACHE 2000 /* sort this many blocks at once */
  180. static void change_key_cache_param(KEY_CACHE *keycache,
  181. ulonglong division_limit,
  182. ulonglong age_threshold);
  183. static int flush_all_key_blocks(KEY_CACHE *keycache,
  184. st_keycache_thread_var *thread_var);
  185. static void wait_on_queue(KEYCACHE_WQUEUE *wqueue, mysql_mutex_t *mutex,
  186. st_keycache_thread_var *thread);
  187. static void release_whole_queue(KEYCACHE_WQUEUE *wqueue);
  188. static void free_block(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  189. BLOCK_LINK *block);
  190. #define KEYCACHE_HASH(f, pos) \
  191. (((ulong)((pos) / keycache->key_cache_block_size) + (ulong)(f)) & \
  192. (keycache->hash_entries - 1))
  193. #define FILE_HASH(f) ((uint)(f) & (CHANGED_BLOCKS_HASH - 1))
  194. #define BLOCK_NUMBER(b) \
  195. ((uint)(((char *)(b) - (char *)keycache->block_root) / sizeof(BLOCK_LINK)))
  196. #ifdef KEYCACHE_TIMEOUT
  197. #define HASH_LINK_NUMBER(h) \
  198. ((uint)(((char *)(h) - (char *)keycache->hash_link_root) / sizeof(HASH_LINK)))
  199. #endif
  200. #if !defined(DBUG_OFF)
  201. static int fail_block(BLOCK_LINK *block);
  202. static int fail_hlink(HASH_LINK *hlink);
  203. static int cache_empty(KEY_CACHE *keycache);
  204. #endif
  205. static inline uint next_power(uint value) {
  206. return (uint)my_round_up_to_next_power((uint32)value) << 1;
  207. }
  208. /*
  209. Initialize a key cache
  210. SYNOPSIS
  211. init_key_cache()
  212. keycache pointer to a key cache data structure
  213. key_cache_block_size size of blocks to keep cached data
  214. use_mem total memory to use for the key cache
  215. division_limit division limit (may be zero)
  216. age_threshold age threshold (may be zero)
  217. RETURN VALUE
  218. number of blocks in the key cache, if successful,
  219. 0 - otherwise.
  220. NOTES.
  221. if keycache->key_cache_inited != 0 we assume that the key cache
  222. is already initialized. This is for now used by myisamchk, but shouldn't
  223. be something that a program should rely on!
  224. It's assumed that no two threads call this function simultaneously
  225. referring to the same key cache handle.
  226. */
  227. int init_key_cache(KEY_CACHE *keycache, ulonglong key_cache_block_size,
  228. size_t use_mem, ulonglong division_limit,
  229. ulonglong age_threshold) {
  230. ulong blocks, hash_links;
  231. size_t length;
  232. int error;
  233. DBUG_ENTER("init_key_cache");
  234. DBUG_ASSERT(key_cache_block_size >= 512);
  235. if (keycache->key_cache_inited && keycache->disk_blocks > 0) {
  236. DBUG_PRINT("warning", ("key cache already in use"));
  237. DBUG_RETURN(0);
  238. }
  239. keycache->global_cache_w_requests = keycache->global_cache_r_requests = 0;
  240. keycache->global_cache_read = keycache->global_cache_write = 0;
  241. keycache->disk_blocks = -1;
  242. if (!keycache->key_cache_inited) {
  243. keycache->key_cache_inited = 1;
  244. /*
  245. Initialize these variables once only.
  246. Their value must survive re-initialization during resizing.
  247. */
  248. keycache->in_resize = 0;
  249. keycache->resize_in_flush = 0;
  250. keycache->cnt_for_resize_op = 0;
  251. keycache->waiting_for_resize_cnt.last_thread = NULL;
  252. keycache->in_init = 0;
  253. mysql_mutex_init(key_KEY_CACHE_cache_lock, &keycache->cache_lock,
  254. MY_MUTEX_INIT_FAST);
  255. keycache->resize_queue.last_thread = NULL;
  256. }
  257. keycache->key_cache_mem_size = use_mem;
  258. keycache->key_cache_block_size = (uint)key_cache_block_size;
  259. DBUG_PRINT("info", ("key_cache_block_size: %llu", key_cache_block_size));
  260. blocks =
  261. (ulong)(use_mem / (sizeof(BLOCK_LINK) + 2 * sizeof(HASH_LINK) +
  262. sizeof(HASH_LINK *) * 5 / 4 + key_cache_block_size));
  263. /* It doesn't make sense to have too few blocks (less than 8) */
  264. if (blocks >= 8) {
  265. for (;;) {
  266. /* Set my_hash_entries to the next bigger 2 power */
  267. if ((keycache->hash_entries = next_power(blocks)) < blocks * 5 / 4)
  268. keycache->hash_entries <<= 1;
  269. hash_links = 2 * blocks;
  270. while ((length =
  271. (ALIGN_SIZE(blocks * sizeof(BLOCK_LINK)) +
  272. ALIGN_SIZE(hash_links * sizeof(HASH_LINK)) +
  273. ALIGN_SIZE(sizeof(HASH_LINK *) * keycache->hash_entries))) +
  274. ((size_t)blocks * keycache->key_cache_block_size) >
  275. use_mem)
  276. blocks--;
  277. /* Allocate memory for cache page buffers */
  278. if ((keycache->block_mem = static_cast<uchar *>(my_malloc(
  279. key_memory_KEY_CACHE,
  280. (size_t)blocks * keycache->key_cache_block_size, MYF(0))))) {
  281. /*
  282. Allocate memory for blocks, hash_links and hash entries;
  283. For each block 2 hash links are allocated
  284. */
  285. if ((keycache->block_root =
  286. (BLOCK_LINK *)my_malloc(key_memory_KEY_CACHE, length, MYF(0))))
  287. break;
  288. my_free(keycache->block_mem);
  289. keycache->block_mem = 0;
  290. }
  291. if (blocks < 8) {
  292. set_my_errno(ENOMEM);
  293. my_error(EE_OUTOFMEMORY, MYF(ME_FATALERROR),
  294. blocks * keycache->key_cache_block_size);
  295. goto err;
  296. }
  297. blocks = blocks / 4 * 3;
  298. }
  299. keycache->blocks_unused = blocks;
  300. keycache->disk_blocks = (int)blocks;
  301. keycache->hash_links = hash_links;
  302. keycache->hash_root =
  303. (HASH_LINK **)((char *)keycache->block_root +
  304. ALIGN_SIZE(blocks * sizeof(BLOCK_LINK)));
  305. keycache->hash_link_root =
  306. (HASH_LINK *)((char *)keycache->hash_root +
  307. ALIGN_SIZE(
  308. (sizeof(HASH_LINK *) * keycache->hash_entries)));
  309. memset(keycache->block_root, 0, keycache->disk_blocks * sizeof(BLOCK_LINK));
  310. memset(keycache->hash_root, 0,
  311. keycache->hash_entries * sizeof(HASH_LINK *));
  312. memset(keycache->hash_link_root, 0,
  313. keycache->hash_links * sizeof(HASH_LINK));
  314. keycache->hash_links_used = 0;
  315. keycache->free_hash_list = NULL;
  316. keycache->blocks_used = keycache->blocks_changed = 0;
  317. keycache->global_blocks_changed = 0;
  318. keycache->blocks_available = 0; /* For debugging */
  319. /* The LRU chain is empty after initialization */
  320. keycache->used_last = NULL;
  321. keycache->used_ins = NULL;
  322. keycache->free_block_list = NULL;
  323. keycache->keycache_time = 0;
  324. keycache->warm_blocks = 0;
  325. keycache->min_warm_blocks =
  326. (division_limit ? blocks * division_limit / 100 + 1 : blocks);
  327. keycache->age_threshold =
  328. (age_threshold ? blocks * age_threshold / 100 : blocks);
  329. keycache->can_be_used = 1;
  330. keycache->waiting_for_hash_link.last_thread = NULL;
  331. keycache->waiting_for_block.last_thread = NULL;
  332. DBUG_PRINT("exit", ("disk_blocks: %d block_root: %p hash_entries: %d\
  333. hash_root: %p hash_links: %d hash_link_root: %p",
  334. keycache->disk_blocks, keycache->block_root,
  335. keycache->hash_entries, keycache->hash_root,
  336. keycache->hash_links, keycache->hash_link_root));
  337. memset(keycache->changed_blocks, 0,
  338. sizeof(keycache->changed_blocks[0]) * CHANGED_BLOCKS_HASH);
  339. memset(keycache->file_blocks, 0,
  340. sizeof(keycache->file_blocks[0]) * CHANGED_BLOCKS_HASH);
  341. } else {
  342. /* key_buffer_size is specified too small. Disable the cache. */
  343. keycache->can_be_used = 0;
  344. }
  345. keycache->blocks = keycache->disk_blocks > 0 ? keycache->disk_blocks : 0;
  346. DBUG_RETURN((int)keycache->disk_blocks);
  347. err:
  348. error = my_errno();
  349. keycache->disk_blocks = 0;
  350. keycache->blocks = 0;
  351. if (keycache->block_mem) {
  352. my_free((uchar *)keycache->block_mem);
  353. keycache->block_mem = NULL;
  354. }
  355. if (keycache->block_root) {
  356. my_free(keycache->block_root);
  357. keycache->block_root = NULL;
  358. }
  359. set_my_errno(error);
  360. keycache->can_be_used = 0;
  361. DBUG_RETURN(0);
  362. }
  363. /*
  364. Resize a key cache
  365. SYNOPSIS
  366. resize_key_cache()
  367. keycache pointer to a key cache data structure
  368. thread_var pointer to thread specific variables
  369. key_cache_block_size size of blocks to keep cached data
  370. use_mem total memory to use for the new key cache
  371. division_limit new division limit (if not zero)
  372. age_threshold new age threshold (if not zero)
  373. RETURN VALUE
  374. number of blocks in the key cache, if successful,
  375. 0 - otherwise.
  376. NOTES.
  377. The function first compares the memory size and the block size parameters
  378. with the key cache values.
  379. If they differ the function free the the memory allocated for the
  380. old key cache blocks by calling the end_key_cache function and
  381. then rebuilds the key cache with new blocks by calling
  382. init_key_cache.
  383. The function starts the operation only when all other threads
  384. performing operations with the key cache let her to proceed
  385. (when cnt_for_resize=0).
  386. */
  387. int resize_key_cache(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  388. ulonglong key_cache_block_size, size_t use_mem,
  389. ulonglong division_limit, ulonglong age_threshold) {
  390. int blocks;
  391. DBUG_ENTER("resize_key_cache");
  392. if (!keycache->key_cache_inited) DBUG_RETURN(keycache->disk_blocks);
  393. if (key_cache_block_size == keycache->key_cache_block_size &&
  394. use_mem == keycache->key_cache_mem_size) {
  395. change_key_cache_param(keycache, division_limit, age_threshold);
  396. DBUG_RETURN(keycache->disk_blocks);
  397. }
  398. mysql_mutex_lock(&keycache->cache_lock);
  399. /*
  400. We may need to wait for another thread which is doing a resize
  401. already. This cannot happen in the MySQL server though. It allows
  402. one resizer only. In set_var.cc keycache->in_init is used to block
  403. multiple attempts.
  404. */
  405. while (keycache->in_resize) {
  406. /* purecov: begin inspected */
  407. wait_on_queue(&keycache->resize_queue, &keycache->cache_lock, thread_var);
  408. /* purecov: end */
  409. }
  410. /*
  411. Mark the operation in progress. This blocks other threads from doing
  412. a resize in parallel. It prohibits new blocks to enter the cache.
  413. Read/write requests can bypass the cache during the flush phase.
  414. */
  415. keycache->in_resize = 1;
  416. /* Need to flush only if keycache is enabled. */
  417. if (keycache->can_be_used) {
  418. /* Start the flush phase. */
  419. keycache->resize_in_flush = 1;
  420. if (flush_all_key_blocks(keycache, thread_var)) {
  421. /* TODO: if this happens, we should write a warning in the log file ! */
  422. keycache->resize_in_flush = 0;
  423. blocks = 0;
  424. keycache->can_be_used = 0;
  425. goto finish;
  426. }
  427. DBUG_ASSERT(cache_empty(keycache));
  428. /* End the flush phase. */
  429. keycache->resize_in_flush = 0;
  430. }
  431. /*
  432. Some direct read/write operations (bypassing the cache) may still be
  433. unfinished. Wait until they are done. If the key cache can be used,
  434. direct I/O is done in increments of key_cache_block_size. That is,
  435. every block is checked if it is in the cache. We need to wait for
  436. pending I/O before re-initializing the cache, because we may change
  437. the block size. Otherwise they could check for blocks at file
  438. positions where the new block division has none. We do also want to
  439. wait for I/O done when (if) the cache was disabled. It must not
  440. run in parallel with normal cache operation.
  441. */
  442. while (keycache->cnt_for_resize_op)
  443. wait_on_queue(&keycache->waiting_for_resize_cnt, &keycache->cache_lock,
  444. thread_var);
  445. /*
  446. Free old cache structures, allocate new structures, and initialize
  447. them. Note that the cache_lock mutex and the resize_queue are left
  448. untouched. We do not lose the cache_lock and will release it only at
  449. the end of this function.
  450. */
  451. end_key_cache(keycache, 0); /* Don't free mutex */
  452. /* The following will work even if use_mem is 0 */
  453. blocks = init_key_cache(keycache, key_cache_block_size, use_mem,
  454. division_limit, age_threshold);
  455. finish:
  456. /*
  457. Mark the resize finished. This allows other threads to start a
  458. resize or to request new cache blocks.
  459. */
  460. keycache->in_resize = 0;
  461. /* Signal waiting threads. */
  462. release_whole_queue(&keycache->resize_queue);
  463. mysql_mutex_unlock(&keycache->cache_lock);
  464. DBUG_RETURN(blocks);
  465. }
  466. /*
  467. Increment counter blocking resize key cache operation
  468. */
  469. static inline void inc_counter_for_resize_op(KEY_CACHE *keycache) {
  470. keycache->cnt_for_resize_op++;
  471. }
  472. /*
  473. Decrement counter blocking resize key cache operation;
  474. Signal the operation to proceed when counter becomes equal zero
  475. */
  476. static inline void dec_counter_for_resize_op(KEY_CACHE *keycache) {
  477. if (!--keycache->cnt_for_resize_op)
  478. release_whole_queue(&keycache->waiting_for_resize_cnt);
  479. }
  480. /*
  481. Change the key cache parameters
  482. SYNOPSIS
  483. change_key_cache_param()
  484. keycache pointer to a key cache data structure
  485. division_limit new division limit (if not zero)
  486. age_threshold new age threshold (if not zero)
  487. RETURN VALUE
  488. none
  489. NOTES.
  490. Presently the function resets the key cache parameters
  491. concerning midpoint insertion strategy - division_limit and
  492. age_threshold.
  493. */
  494. static void change_key_cache_param(KEY_CACHE *keycache,
  495. ulonglong division_limit,
  496. ulonglong age_threshold) {
  497. DBUG_ENTER("change_key_cache_param");
  498. mysql_mutex_lock(&keycache->cache_lock);
  499. if (division_limit)
  500. keycache->min_warm_blocks =
  501. (keycache->disk_blocks * division_limit / 100 + 1);
  502. if (age_threshold)
  503. keycache->age_threshold = (keycache->disk_blocks * age_threshold / 100);
  504. mysql_mutex_unlock(&keycache->cache_lock);
  505. DBUG_VOID_RETURN;
  506. }
  507. /*
  508. Remove key_cache from memory
  509. SYNOPSIS
  510. end_key_cache()
  511. keycache key cache handle
  512. cleanup Complete free (Free also mutex for key cache)
  513. RETURN VALUE
  514. none
  515. */
  516. void end_key_cache(KEY_CACHE *keycache, bool cleanup) {
  517. DBUG_ENTER("end_key_cache");
  518. DBUG_PRINT("enter", ("key_cache: %p", keycache));
  519. if (!keycache->key_cache_inited) DBUG_VOID_RETURN;
  520. if (keycache->disk_blocks > 0) {
  521. if (keycache->block_mem) {
  522. my_free((uchar *)keycache->block_mem);
  523. keycache->block_mem = NULL;
  524. my_free(keycache->block_root);
  525. keycache->block_root = NULL;
  526. }
  527. keycache->disk_blocks = -1;
  528. /* Reset blocks_changed to be safe if flush_all_key_blocks is called */
  529. keycache->blocks_changed = 0;
  530. }
  531. DBUG_PRINT("status", ("used: %lu changed: %lu w_requests: %lu "
  532. "writes: %lu r_requests: %lu reads: %lu",
  533. keycache->blocks_used, keycache->global_blocks_changed,
  534. (ulong)keycache->global_cache_w_requests,
  535. (ulong)keycache->global_cache_write,
  536. (ulong)keycache->global_cache_r_requests,
  537. (ulong)keycache->global_cache_read));
  538. /*
  539. Reset these values to be able to detect a disabled key cache.
  540. See Bug#44068 (RESTORE can disable the MyISAM Key Cache).
  541. */
  542. keycache->blocks_used = 0;
  543. keycache->blocks_unused = 0;
  544. if (cleanup) {
  545. mysql_mutex_destroy(&keycache->cache_lock);
  546. keycache->key_cache_inited = keycache->can_be_used = 0;
  547. }
  548. DBUG_VOID_RETURN;
  549. } /* end_key_cache */
  550. /**
  551. Link a thread into double-linked queue of waiting threads.
  552. @param wqueue pointer to the queue structure
  553. @param thread pointer to the keycache variables for the
  554. thread to be added to the queue
  555. Queue is represented by a circular list of the keycache variable structures.
  556. Since each thread has its own keycache variables, this is equal to a list
  557. of threads. The list is double-linked of the type (**prev,*next), accessed by
  558. a pointer to the last element.
  559. */
  560. static void link_into_queue(KEYCACHE_WQUEUE *wqueue,
  561. st_keycache_thread_var *thread) {
  562. st_keycache_thread_var *last;
  563. DBUG_ASSERT(!thread->next && !thread->prev);
  564. if (!(last = wqueue->last_thread)) {
  565. /* Queue is empty */
  566. thread->next = thread;
  567. thread->prev = &thread->next;
  568. } else {
  569. thread->prev = last->next->prev;
  570. last->next->prev = &thread->next;
  571. thread->next = last->next;
  572. last->next = thread;
  573. }
  574. wqueue->last_thread = thread;
  575. }
  576. /**
  577. Unlink a thread from double-linked queue of waiting threads
  578. @param wqueue pointer to the queue structure
  579. @param thread pointer to the keycache variables for the
  580. thread to be removed to the queue
  581. @note See link_into_queue
  582. */
  583. static void unlink_from_queue(KEYCACHE_WQUEUE *wqueue,
  584. st_keycache_thread_var *thread) {
  585. DBUG_ASSERT(thread->next && thread->prev);
  586. if (thread->next == thread) /* The queue contains only one member */
  587. wqueue->last_thread = NULL;
  588. else {
  589. thread->next->prev = thread->prev;
  590. *thread->prev = thread->next;
  591. if (wqueue->last_thread == thread)
  592. wqueue->last_thread =
  593. STRUCT_PTR(st_keycache_thread_var, next, thread->prev);
  594. }
  595. thread->next = NULL;
  596. #if !defined(DBUG_OFF)
  597. /*
  598. This makes it easier to see it's not in a chain during debugging.
  599. And some DBUG_ASSERT() rely on it.
  600. */
  601. thread->prev = NULL;
  602. #endif
  603. }
  604. /*
  605. Add a thread to single-linked queue of waiting threads
  606. SYNOPSIS
  607. wait_on_queue()
  608. wqueue Pointer to the queue structure.
  609. mutex Cache_lock to acquire after awake.
  610. thread Thread to be added
  611. RETURN VALUE
  612. none
  613. NOTES.
  614. Queue is represented by a circular list of the thread structures
  615. The list is single-linked of the type (*next), accessed by a pointer
  616. to the last element.
  617. The function protects against stray signals by verifying that the
  618. current thread is unlinked from the queue when awaking. However,
  619. since several threads can wait for the same event, it might be
  620. necessary for the caller of the function to check again if the
  621. condition for awake is indeed matched.
  622. */
  623. static void wait_on_queue(KEYCACHE_WQUEUE *wqueue, mysql_mutex_t *mutex,
  624. st_keycache_thread_var *thread) {
  625. st_keycache_thread_var *last;
  626. /* Add to queue. */
  627. DBUG_ASSERT(!thread->next);
  628. DBUG_ASSERT(!thread->prev); /* Not required, but must be true anyway. */
  629. if (!(last = wqueue->last_thread))
  630. thread->next = thread;
  631. else {
  632. thread->next = last->next;
  633. last->next = thread;
  634. }
  635. wqueue->last_thread = thread;
  636. /*
  637. Wait until thread is removed from queue by the signalling thread.
  638. The loop protects against stray signals.
  639. */
  640. do {
  641. mysql_cond_wait(&thread->suspend, mutex);
  642. } while (thread->next);
  643. }
  644. /*
  645. Remove all threads from queue signaling them to proceed
  646. SYNOPSIS
  647. release_whole_queue()
  648. wqueue pointer to the queue structure
  649. RETURN VALUE
  650. none
  651. NOTES.
  652. See notes for wait_on_queue().
  653. When removed from the queue each thread is signaled via condition
  654. variable thread->suspend.
  655. */
  656. static void release_whole_queue(KEYCACHE_WQUEUE *wqueue) {
  657. st_keycache_thread_var *last;
  658. st_keycache_thread_var *next;
  659. st_keycache_thread_var *thread;
  660. /* Queue may be empty. */
  661. if (!(last = wqueue->last_thread)) return;
  662. next = last->next;
  663. do {
  664. thread = next;
  665. /* Signal the thread. */
  666. mysql_cond_signal(&thread->suspend);
  667. /* Take thread from queue. */
  668. next = thread->next;
  669. thread->next = NULL;
  670. } while (thread != last);
  671. /* Now queue is definitely empty. */
  672. wqueue->last_thread = NULL;
  673. }
  674. /*
  675. Unlink a block from the chain of dirty/clean blocks
  676. */
  677. static inline void unlink_changed(BLOCK_LINK *block) {
  678. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  679. if (block->next_changed)
  680. block->next_changed->prev_changed = block->prev_changed;
  681. *block->prev_changed = block->next_changed;
  682. #if !defined(DBUG_OFF)
  683. /*
  684. This makes it easier to see it's not in a chain during debugging.
  685. And some DBUG_ASSERT() rely on it.
  686. */
  687. block->next_changed = NULL;
  688. block->prev_changed = NULL;
  689. #endif
  690. }
  691. /*
  692. Link a block into the chain of dirty/clean blocks
  693. */
  694. static inline void link_changed(BLOCK_LINK *block, BLOCK_LINK **phead) {
  695. DBUG_ASSERT(!block->next_changed);
  696. DBUG_ASSERT(!block->prev_changed);
  697. block->prev_changed = phead;
  698. if ((block->next_changed = *phead))
  699. (*phead)->prev_changed = &block->next_changed;
  700. *phead = block;
  701. }
  702. /*
  703. Link a block in a chain of clean blocks of a file.
  704. SYNOPSIS
  705. link_to_file_list()
  706. keycache Key cache handle
  707. block Block to relink
  708. file File to be linked to
  709. unlink If to unlink first
  710. DESCRIPTION
  711. Unlink a block from whichever chain it is linked in, if it's
  712. asked for, and link it to the chain of clean blocks of the
  713. specified file.
  714. NOTE
  715. Please do never set/clear BLOCK_CHANGED outside of
  716. link_to_file_list() or link_to_changed_list().
  717. You would risk to damage correct counting of changed blocks
  718. and to find blocks in the wrong hash.
  719. RETURN
  720. void
  721. */
  722. static void link_to_file_list(KEY_CACHE *keycache, BLOCK_LINK *block, int file,
  723. bool unlink_block) {
  724. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  725. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  726. DBUG_ASSERT(block->hash_link->file == file);
  727. if (unlink_block) unlink_changed(block);
  728. link_changed(block, &keycache->file_blocks[FILE_HASH(file)]);
  729. if (block->status & BLOCK_CHANGED) {
  730. block->status &= ~BLOCK_CHANGED;
  731. keycache->blocks_changed--;
  732. keycache->global_blocks_changed--;
  733. }
  734. }
  735. /*
  736. Re-link a block from the clean chain to the dirty chain of a file.
  737. SYNOPSIS
  738. link_to_changed_list()
  739. keycache key cache handle
  740. block block to relink
  741. DESCRIPTION
  742. Unlink a block from the chain of clean blocks of a file
  743. and link it to the chain of dirty blocks of the same file.
  744. NOTE
  745. Please do never set/clear BLOCK_CHANGED outside of
  746. link_to_file_list() or link_to_changed_list().
  747. You would risk to damage correct counting of changed blocks
  748. and to find blocks in the wrong hash.
  749. RETURN
  750. void
  751. */
  752. static void link_to_changed_list(KEY_CACHE *keycache, BLOCK_LINK *block) {
  753. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  754. DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
  755. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  756. unlink_changed(block);
  757. link_changed(block,
  758. &keycache->changed_blocks[FILE_HASH(block->hash_link->file)]);
  759. block->status |= BLOCK_CHANGED;
  760. keycache->blocks_changed++;
  761. keycache->global_blocks_changed++;
  762. }
  763. /*
  764. Link a block to the LRU chain at the beginning or at the end of
  765. one of two parts.
  766. SYNOPSIS
  767. link_block()
  768. keycache pointer to a key cache data structure
  769. block pointer to the block to link to the LRU chain
  770. hot <-> to link the block into the hot subchain
  771. at_end <-> to link the block at the end of the subchain
  772. RETURN VALUE
  773. none
  774. NOTES.
  775. The LRU ring is represented by a circular list of block structures.
  776. The list is double-linked of the type (**prev,*next) type.
  777. The LRU ring is divided into two parts - hot and warm.
  778. There are two pointers to access the last blocks of these two
  779. parts. The beginning of the warm part follows right after the
  780. end of the hot part.
  781. Only blocks of the warm part can be used for eviction.
  782. The first block from the beginning of this subchain is always
  783. taken for eviction (keycache->last_used->next)
  784. LRU chain: +------+ H O T +------+
  785. +----| end |----...<----| beg |----+
  786. | +------+last +------+ |
  787. v<-link in latest hot (new end) |
  788. | link in latest warm (new end)->^
  789. | +------+ W A R M +------+ |
  790. +----| beg |---->...----| end |----+
  791. +------+ +------+ins
  792. first for eviction
  793. It is also possible that the block is selected for eviction and thus
  794. not linked in the LRU ring.
  795. */
  796. static void link_block(KEY_CACHE *keycache, BLOCK_LINK *block, bool hot,
  797. bool at_end) {
  798. BLOCK_LINK *ins;
  799. BLOCK_LINK **pins;
  800. DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
  801. DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  802. DBUG_ASSERT(!block->requests);
  803. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  804. DBUG_ASSERT(!block->next_used);
  805. DBUG_ASSERT(!block->prev_used);
  806. if (!hot && keycache->waiting_for_block.last_thread) {
  807. /* Signal that in the LRU warm sub-chain an available block has appeared */
  808. st_keycache_thread_var *last_thread =
  809. keycache->waiting_for_block.last_thread;
  810. st_keycache_thread_var *first_thread = last_thread->next;
  811. st_keycache_thread_var *next_thread = first_thread;
  812. HASH_LINK *hash_link = (HASH_LINK *)first_thread->opt_info;
  813. st_keycache_thread_var *thread;
  814. do {
  815. thread = next_thread;
  816. next_thread = thread->next;
  817. /*
  818. We notify about the event all threads that ask
  819. for the same page as the first thread in the queue
  820. */
  821. if ((HASH_LINK *)thread->opt_info == hash_link) {
  822. mysql_cond_signal(&thread->suspend);
  823. unlink_from_queue(&keycache->waiting_for_block, thread);
  824. block->requests++;
  825. }
  826. } while (thread != last_thread);
  827. hash_link->block = block;
  828. /*
  829. NOTE: We assigned the block to the hash_link and signalled the
  830. requesting thread(s). But it is possible that other threads runs
  831. first. These threads see the hash_link assigned to a block which
  832. is assigned to another hash_link and not marked BLOCK_IN_SWITCH.
  833. This can be a problem for functions that do not select the block
  834. via its hash_link: flush and free. They do only see a block which
  835. is in a "normal" state and don't know that it will be evicted soon.
  836. We cannot set BLOCK_IN_SWITCH here because only one of the
  837. requesting threads must handle the eviction. All others must wait
  838. for it to complete. If we set the flag here, the threads would not
  839. know who is in charge of the eviction. Without the flag, the first
  840. thread takes the stick and sets the flag.
  841. But we need to note in the block that is has been selected for
  842. eviction. It must not be freed. The evicting thread will not
  843. expect the block in the free list. Before freeing we could also
  844. check if block->requests > 1. But I think including another flag
  845. in the check of block->status is slightly more efficient and
  846. probably easier to read.
  847. */
  848. block->status |= BLOCK_IN_EVICTION;
  849. return;
  850. }
  851. pins = hot ? &keycache->used_ins : &keycache->used_last;
  852. ins = *pins;
  853. if (ins) {
  854. ins->next_used->prev_used = &block->next_used;
  855. block->next_used = ins->next_used;
  856. block->prev_used = &ins->next_used;
  857. ins->next_used = block;
  858. if (at_end) *pins = block;
  859. } else {
  860. /* The LRU ring is empty. Let the block point to itself. */
  861. keycache->used_last = keycache->used_ins = block->next_used = block;
  862. block->prev_used = &block->next_used;
  863. }
  864. DBUG_ASSERT((ulong)keycache->blocks_available <= keycache->blocks_used);
  865. }
  866. /*
  867. Unlink a block from the LRU chain
  868. SYNOPSIS
  869. unlink_block()
  870. keycache pointer to a key cache data structure
  871. block pointer to the block to unlink from the LRU chain
  872. RETURN VALUE
  873. none
  874. NOTES.
  875. See NOTES for link_block
  876. */
  877. static void unlink_block(KEY_CACHE *keycache, BLOCK_LINK *block) {
  878. DBUG_ASSERT((block->status & ~BLOCK_CHANGED) == (BLOCK_READ | BLOCK_IN_USE));
  879. DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  880. DBUG_ASSERT(!block->requests);
  881. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  882. DBUG_ASSERT(block->next_used && block->prev_used &&
  883. (block->next_used->prev_used == &block->next_used) &&
  884. (*block->prev_used == block));
  885. if (block->next_used == block) /* The list contains only one member */
  886. keycache->used_last = keycache->used_ins = NULL;
  887. else {
  888. block->next_used->prev_used = block->prev_used;
  889. *block->prev_used = block->next_used;
  890. if (keycache->used_last == block)
  891. keycache->used_last = STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
  892. if (keycache->used_ins == block)
  893. keycache->used_ins = STRUCT_PTR(BLOCK_LINK, next_used, block->prev_used);
  894. }
  895. block->next_used = NULL;
  896. #if !defined(DBUG_OFF)
  897. /*
  898. This makes it easier to see it's not in a chain during debugging.
  899. And some DBUG_ASSERT() rely on it.
  900. */
  901. block->prev_used = NULL;
  902. #endif
  903. }
  904. /*
  905. Register requests for a block.
  906. SYNOPSIS
  907. reg_requests()
  908. keycache Pointer to a key cache data structure.
  909. block Pointer to the block to register a request on.
  910. count Number of requests. Always 1.
  911. NOTE
  912. The first request unlinks the block from the LRU ring. This means
  913. that it is protected against eveiction.
  914. RETURN
  915. void
  916. */
  917. static void reg_requests(KEY_CACHE *keycache, BLOCK_LINK *block, int count) {
  918. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  919. DBUG_ASSERT(block->hash_link);
  920. if (!block->requests) unlink_block(keycache, block);
  921. block->requests += count;
  922. }
  923. /*
  924. Unregister request for a block
  925. linking it to the LRU chain if it's the last request
  926. SYNOPSIS
  927. unreg_request()
  928. keycache pointer to a key cache data structure
  929. block pointer to the block to link to the LRU chain
  930. at_end <-> to link the block at the end of the LRU chain
  931. RETURN VALUE
  932. none
  933. NOTES.
  934. Every linking to the LRU ring decrements by one a special block
  935. counter (if it's positive). If the at_end parameter is true the block is
  936. added either at the end of warm sub-chain or at the end of hot sub-chain.
  937. It is added to the hot subchain if its counter is zero and number of
  938. blocks in warm sub-chain is not less than some low limit (determined by
  939. the division_limit parameter). Otherwise the block is added to the warm
  940. sub-chain. If the at_end parameter is false the block is always added
  941. at beginning of the warm sub-chain.
  942. Thus a warm block can be promoted to the hot sub-chain when its counter
  943. becomes zero for the first time.
  944. At the same time the block at the very beginning of the hot subchain
  945. might be moved to the beginning of the warm subchain if it stays untouched
  946. for a too long time (this time is determined by parameter age_threshold).
  947. It is also possible that the block is selected for eviction and thus
  948. not linked in the LRU ring.
  949. */
  950. static void unreg_request(KEY_CACHE *keycache, BLOCK_LINK *block, int at_end) {
  951. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  952. DBUG_ASSERT(block->hash_link); /*backptr to block NULL from free_block()*/
  953. DBUG_ASSERT(block->requests);
  954. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  955. DBUG_ASSERT(!block->next_used);
  956. DBUG_ASSERT(!block->prev_used);
  957. /*
  958. Unregister the request, but do not link erroneous blocks into the
  959. LRU ring.
  960. */
  961. if (!--block->requests && !(block->status & BLOCK_ERROR)) {
  962. bool hot;
  963. if (block->hits_left) block->hits_left--;
  964. hot = !block->hits_left && at_end &&
  965. keycache->warm_blocks > keycache->min_warm_blocks;
  966. if (hot) {
  967. if (block->temperature == BLOCK_WARM) keycache->warm_blocks--;
  968. block->temperature = BLOCK_HOT;
  969. }
  970. link_block(keycache, block, hot, at_end);
  971. block->last_hit_time = keycache->keycache_time;
  972. keycache->keycache_time++;
  973. /*
  974. At this place, the block might be in the LRU ring or not. If an
  975. evicter was waiting for a block, it was selected for eviction and
  976. not linked in the LRU ring.
  977. */
  978. /*
  979. Check if we should link a hot block to the warm block sub-chain.
  980. It is possible that we select the same block as above. But it can
  981. also be another block. In any case a block from the LRU ring is
  982. selected. In other words it works even if the above block was
  983. selected for eviction and not linked in the LRU ring. Since this
  984. happens only if the LRU ring is empty, the block selected below
  985. would be NULL and the rest of the function skipped.
  986. */
  987. block = keycache->used_ins;
  988. if (block && keycache->keycache_time - block->last_hit_time >
  989. keycache->age_threshold) {
  990. unlink_block(keycache, block);
  991. link_block(keycache, block, 0, 0);
  992. if (block->temperature != BLOCK_WARM) {
  993. keycache->warm_blocks++;
  994. block->temperature = BLOCK_WARM;
  995. }
  996. }
  997. }
  998. }
  999. /*
  1000. Remove a reader of the page in block
  1001. */
  1002. static void remove_reader(BLOCK_LINK *block) {
  1003. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1004. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  1005. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  1006. DBUG_ASSERT(!block->next_used);
  1007. DBUG_ASSERT(!block->prev_used);
  1008. DBUG_ASSERT(block->hash_link->requests);
  1009. if (!--block->hash_link->requests && block->condvar)
  1010. mysql_cond_signal(block->condvar);
  1011. }
  1012. /*
  1013. Wait until the last reader of the page in block
  1014. signals on its termination
  1015. */
  1016. static void wait_for_readers(KEY_CACHE *keycache, BLOCK_LINK *block,
  1017. st_keycache_thread_var *thread) {
  1018. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1019. DBUG_ASSERT(!(block->status & (BLOCK_IN_FLUSH | BLOCK_CHANGED)));
  1020. DBUG_ASSERT(block->hash_link);
  1021. DBUG_ASSERT(block->hash_link->block == block);
  1022. /* Linked in file_blocks or changed_blocks hash. */
  1023. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  1024. /* Not linked in LRU ring. */
  1025. DBUG_ASSERT(!block->next_used);
  1026. DBUG_ASSERT(!block->prev_used);
  1027. while (block->hash_link->requests) {
  1028. /* There must be no other waiter. We have no queue here. */
  1029. DBUG_ASSERT(!block->condvar);
  1030. block->condvar = &thread->suspend;
  1031. mysql_cond_wait(&thread->suspend, &keycache->cache_lock);
  1032. block->condvar = NULL;
  1033. }
  1034. }
  1035. /*
  1036. Add a hash link to a bucket in the hash_table
  1037. */
  1038. static inline void link_hash(HASH_LINK **start, HASH_LINK *hash_link) {
  1039. if (*start) (*start)->prev = &hash_link->next;
  1040. hash_link->next = *start;
  1041. hash_link->prev = start;
  1042. *start = hash_link;
  1043. }
  1044. /*
  1045. Remove a hash link from the hash table
  1046. */
  1047. static void unlink_hash(KEY_CACHE *keycache, HASH_LINK *hash_link) {
  1048. DBUG_ASSERT(hash_link->requests == 0);
  1049. if ((*hash_link->prev = hash_link->next))
  1050. hash_link->next->prev = hash_link->prev;
  1051. hash_link->block = NULL;
  1052. if (keycache->waiting_for_hash_link.last_thread) {
  1053. /* Signal that a free hash link has appeared */
  1054. st_keycache_thread_var *last_thread =
  1055. keycache->waiting_for_hash_link.last_thread;
  1056. st_keycache_thread_var *first_thread = last_thread->next;
  1057. st_keycache_thread_var *next_thread = first_thread;
  1058. KEYCACHE_PAGE *first_page = (KEYCACHE_PAGE *)(first_thread->opt_info);
  1059. st_keycache_thread_var *thread;
  1060. hash_link->file = first_page->file;
  1061. hash_link->diskpos = first_page->filepos;
  1062. do {
  1063. KEYCACHE_PAGE *page;
  1064. thread = next_thread;
  1065. page = (KEYCACHE_PAGE *)thread->opt_info;
  1066. next_thread = thread->next;
  1067. /*
  1068. We notify about the event all threads that ask
  1069. for the same page as the first thread in the queue
  1070. */
  1071. if (page->file == hash_link->file &&
  1072. page->filepos == hash_link->diskpos) {
  1073. mysql_cond_signal(&thread->suspend);
  1074. unlink_from_queue(&keycache->waiting_for_hash_link, thread);
  1075. }
  1076. } while (thread != last_thread);
  1077. link_hash(
  1078. &keycache
  1079. ->hash_root[KEYCACHE_HASH(hash_link->file, hash_link->diskpos)],
  1080. hash_link);
  1081. return;
  1082. }
  1083. hash_link->next = keycache->free_hash_list;
  1084. keycache->free_hash_list = hash_link;
  1085. }
  1086. /*
  1087. Get the hash link for a page
  1088. */
  1089. static HASH_LINK *get_hash_link(KEY_CACHE *keycache, int file, my_off_t filepos,
  1090. st_keycache_thread_var *thread) {
  1091. HASH_LINK *hash_link, **start;
  1092. #ifndef DBUG_OFF
  1093. int cnt;
  1094. #endif
  1095. restart:
  1096. /*
  1097. Find the bucket in the hash table for the pair (file, filepos);
  1098. start contains the head of the bucket list,
  1099. hash_link points to the first member of the list
  1100. */
  1101. hash_link = *(start = &keycache->hash_root[KEYCACHE_HASH(file, filepos)]);
  1102. #ifndef DBUG_OFF
  1103. cnt = 0;
  1104. #endif
  1105. /* Look for an element for the pair (file, filepos) in the bucket chain */
  1106. while (hash_link &&
  1107. (hash_link->diskpos != filepos || hash_link->file != file)) {
  1108. hash_link = hash_link->next;
  1109. #ifndef DBUG_OFF
  1110. cnt++;
  1111. DBUG_ASSERT(cnt <= keycache->hash_links_used);
  1112. #endif
  1113. }
  1114. if (!hash_link) {
  1115. /* There is no hash link in the hash table for the pair (file, filepos) */
  1116. if (keycache->free_hash_list) {
  1117. hash_link = keycache->free_hash_list;
  1118. keycache->free_hash_list = hash_link->next;
  1119. } else if (keycache->hash_links_used < keycache->hash_links) {
  1120. hash_link = &keycache->hash_link_root[keycache->hash_links_used++];
  1121. } else {
  1122. /* Wait for a free hash link */
  1123. KEYCACHE_PAGE page;
  1124. page.file = file;
  1125. page.filepos = filepos;
  1126. thread->opt_info = (void *)&page;
  1127. link_into_queue(&keycache->waiting_for_hash_link, thread);
  1128. mysql_cond_wait(&thread->suspend, &keycache->cache_lock);
  1129. thread->opt_info = NULL;
  1130. goto restart;
  1131. }
  1132. hash_link->file = file;
  1133. hash_link->diskpos = filepos;
  1134. link_hash(start, hash_link);
  1135. }
  1136. /* Register the request for the page */
  1137. hash_link->requests++;
  1138. return hash_link;
  1139. }
  1140. /*
  1141. Get a block for the file page requested by a keycache read/write operation;
  1142. If the page is not in the cache return a free block, if there is none
  1143. return the lru block after saving its buffer if the page is dirty.
  1144. SYNOPSIS
  1145. find_key_block()
  1146. keycache pointer to a key cache data structure
  1147. thread pointer to thread specific variables
  1148. file handler for the file to read page from
  1149. filepos position of the page in the file
  1150. init_hits_left how initialize the block counter for the page
  1151. wrmode <-> get for writing
  1152. page_st out {PAGE_READ,PAGE_TO_BE_READ,PAGE_WAIT_TO_BE_READ}
  1153. RETURN VALUE
  1154. Pointer to the found block if successful, 0 - otherwise
  1155. NOTES.
  1156. For the page from file positioned at filepos the function checks whether
  1157. the page is in the key cache specified by the first parameter.
  1158. If this is the case it immediately returns the block.
  1159. If not, the function first chooses a block for this page. If there is
  1160. no not used blocks in the key cache yet, the function takes the block
  1161. at the very beginning of the warm sub-chain. It saves the page in that
  1162. block if it's dirty before returning the pointer to it.
  1163. The function returns in the page_st parameter the following values:
  1164. PAGE_READ - if page already in the block,
  1165. PAGE_TO_BE_READ - if it is to be read yet by the current thread
  1166. WAIT_TO_BE_READ - if it is to be read by another thread
  1167. If an error occurs THE BLOCK_ERROR bit is set in the block status.
  1168. It might happen that there are no blocks in LRU chain (in warm part) -
  1169. all blocks are unlinked for some read/write operations. Then the function
  1170. waits until first of this operations links any block back.
  1171. */
  1172. static BLOCK_LINK *find_key_block(KEY_CACHE *keycache,
  1173. st_keycache_thread_var *thread, File file,
  1174. my_off_t filepos, int init_hits_left,
  1175. int wrmode, int *page_st) {
  1176. HASH_LINK *hash_link;
  1177. BLOCK_LINK *block;
  1178. int error = 0;
  1179. int page_status;
  1180. DBUG_ENTER("find_key_block");
  1181. DBUG_PRINT("enter",
  1182. ("fd: %d pos: %lu wrmode: %d", file, (ulong)filepos, wrmode));
  1183. restart:
  1184. /*
  1185. If the flush phase of a resize operation fails, the cache is left
  1186. unusable. This will be detected only after "goto restart".
  1187. */
  1188. if (!keycache->can_be_used) DBUG_RETURN(0);
  1189. /*
  1190. Find the hash_link for the requested file block (file, filepos). We
  1191. do always get a hash_link here. It has registered our request so
  1192. that no other thread can use it for another file block until we
  1193. release the request (which is done by remove_reader() usually). The
  1194. hash_link can have a block assigned to it or not. If there is a
  1195. block, it may be assigned to this hash_link or not. In cases where a
  1196. block is evicted from the cache, it is taken from the LRU ring and
  1197. referenced by the new hash_link. But the block can still be assigned
  1198. to its old hash_link for some time if it needs to be flushed first,
  1199. or if there are other threads still reading it.
  1200. Summary:
  1201. hash_link is always returned.
  1202. hash_link->block can be:
  1203. - NULL or
  1204. - not assigned to this hash_link or
  1205. - assigned to this hash_link. If assigned, the block can have
  1206. - invalid data (when freshly assigned) or
  1207. - valid data. Valid data can be
  1208. - changed over the file contents (dirty) or
  1209. - not changed (clean).
  1210. */
  1211. hash_link = get_hash_link(keycache, file, filepos, thread);
  1212. DBUG_ASSERT((hash_link->file == file) && (hash_link->diskpos == filepos));
  1213. page_status = -1;
  1214. if ((block = hash_link->block) && block->hash_link == hash_link &&
  1215. (block->status & BLOCK_READ)) {
  1216. /* Assigned block with valid (changed or unchanged) contents. */
  1217. page_status = PAGE_READ;
  1218. }
  1219. /*
  1220. else (page_status == -1)
  1221. - block == NULL or
  1222. - block not assigned to this hash_link or
  1223. - block assigned but not yet read from file (invalid data).
  1224. */
  1225. if (keycache->in_resize) {
  1226. /* This is a request during a resize operation */
  1227. if (!block) {
  1228. /*
  1229. The file block is not in the cache. We don't need it in the
  1230. cache: we are going to read or write directly to file. Cancel
  1231. the request. We can simply decrement hash_link->requests because
  1232. we did not release cache_lock since increasing it. So no other
  1233. thread can wait for our request to become released.
  1234. */
  1235. if (hash_link->requests == 1) {
  1236. /*
  1237. We are the only one to request this hash_link (this file/pos).
  1238. Free the hash_link.
  1239. */
  1240. hash_link->requests--;
  1241. unlink_hash(keycache, hash_link);
  1242. DBUG_RETURN(0);
  1243. }
  1244. /*
  1245. More requests on the hash_link. Someone tries to evict a block
  1246. for this hash_link (could have started before resizing started).
  1247. This means that the LRU ring is empty. Otherwise a block could
  1248. be assigned immediately. Behave like a thread that wants to
  1249. evict a block for this file/pos. Add to the queue of threads
  1250. waiting for a block. Wait until there is one assigned.
  1251. Refresh the request on the hash-link so that it cannot be reused
  1252. for another file/pos.
  1253. */
  1254. thread->opt_info = (void *)hash_link;
  1255. link_into_queue(&keycache->waiting_for_block, thread);
  1256. do {
  1257. mysql_cond_wait(&thread->suspend, &keycache->cache_lock);
  1258. } while (thread->next);
  1259. thread->opt_info = NULL;
  1260. /*
  1261. A block should now be assigned to the hash_link. But it may
  1262. still need to be evicted. Anyway, we should re-check the
  1263. situation. page_status must be set correctly.
  1264. */
  1265. hash_link->requests--;
  1266. goto restart;
  1267. } /* end of if (!block) */
  1268. /*
  1269. There is a block for this file/pos in the cache. Register a
  1270. request on it. This unlinks it from the LRU ring (if it is there)
  1271. and hence protects it against eviction (if not already in
  1272. eviction). We need this for returning the block to the caller, for
  1273. calling remove_reader() (for debugging purposes), and for calling
  1274. free_block(). The only case where we don't need the request is if
  1275. the block is in eviction. In that case we have to unregister the
  1276. request later.
  1277. */
  1278. reg_requests(keycache, block, 1);
  1279. if (page_status != PAGE_READ) {
  1280. /*
  1281. - block not assigned to this hash_link or
  1282. - block assigned but not yet read from file (invalid data).
  1283. This must be a block in eviction. It will be read soon. We need
  1284. to wait here until this happened. Otherwise the caller could
  1285. access a wrong block or a block which is in read. While waiting
  1286. we cannot lose hash_link nor block. We have registered a request
  1287. on the hash_link. Everything can happen to the block but changes
  1288. in the hash_link -> block relationship. In other words:
  1289. everything can happen to the block but free or another completed
  1290. eviction.
  1291. Note that we bahave like a secondary requestor here. We just
  1292. cannot return with PAGE_WAIT_TO_BE_READ. This would work for
  1293. read requests and writes on dirty blocks that are not in flush
  1294. only. Waiting here on COND_FOR_REQUESTED works in all
  1295. situations.
  1296. */
  1297. DBUG_ASSERT(
  1298. ((block->hash_link != hash_link) &&
  1299. (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
  1300. ((block->hash_link == hash_link) && !(block->status & BLOCK_READ)));
  1301. wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock,
  1302. thread);
  1303. /*
  1304. Here we can trust that the block has been assigned to this
  1305. hash_link (block->hash_link == hash_link) and read into the
  1306. buffer (BLOCK_READ). The worst things possible here are that the
  1307. block is in free (BLOCK_REASSIGNED). But the block is still
  1308. assigned to the hash_link. The freeing thread waits until we
  1309. release our request on the hash_link. The block must not be
  1310. again in eviction because we registered an request on it before
  1311. starting to wait.
  1312. */
  1313. DBUG_ASSERT(block->hash_link == hash_link);
  1314. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1315. DBUG_ASSERT(!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH)));
  1316. }
  1317. /*
  1318. The block is in the cache. Assigned to the hash_link. Valid data.
  1319. Note that in case of page_st == PAGE_READ, the block can be marked
  1320. for eviction. In any case it can be marked for freeing.
  1321. */
  1322. if (!wrmode) {
  1323. /* A reader can just read the block. */
  1324. *page_st = PAGE_READ;
  1325. DBUG_ASSERT((hash_link->file == file) &&
  1326. (hash_link->diskpos == filepos) &&
  1327. (block->hash_link == hash_link));
  1328. DBUG_RETURN(block);
  1329. }
  1330. /*
  1331. This is a writer. No two writers for the same block can exist.
  1332. This must be assured by locks outside of the key cache.
  1333. */
  1334. DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));
  1335. while (block->status & BLOCK_IN_FLUSH) {
  1336. /*
  1337. Wait until the block is flushed to file. Do not release the
  1338. request on the hash_link yet to prevent that the block is freed
  1339. or reassigned while we wait. While we wait, several things can
  1340. happen to the block, including another flush. But the block
  1341. cannot be reassigned to another hash_link until we release our
  1342. request on it. But it can be marked BLOCK_REASSIGNED from free
  1343. or eviction, while they wait for us to release the hash_link.
  1344. */
  1345. wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock,
  1346. thread);
  1347. /*
  1348. If the flush phase failed, the resize could have finished while
  1349. we waited here.
  1350. */
  1351. if (!keycache->in_resize) {
  1352. remove_reader(block);
  1353. unreg_request(keycache, block, 1);
  1354. goto restart;
  1355. }
  1356. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1357. DBUG_ASSERT(!(block->status & BLOCK_FOR_UPDATE) || fail_block(block));
  1358. DBUG_ASSERT(block->hash_link == hash_link);
  1359. }
  1360. if (block->status & BLOCK_CHANGED) {
  1361. /*
  1362. We want to write a block with changed contents. If the cache
  1363. block size is bigger than the callers block size (e.g. MyISAM),
  1364. the caller may replace part of the block only. Changes of the
  1365. other part of the block must be preserved. Since the block has
  1366. not yet been selected for flush, we can still add our changes.
  1367. */
  1368. *page_st = PAGE_READ;
  1369. DBUG_ASSERT((hash_link->file == file) &&
  1370. (hash_link->diskpos == filepos) &&
  1371. (block->hash_link == hash_link));
  1372. DBUG_RETURN(block);
  1373. }
  1374. /*
  1375. This is a write request for a clean block. We do not want to have
  1376. new dirty blocks in the cache while resizing. We will free the
  1377. block and write directly to file. If the block is in eviction or
  1378. in free, we just let it go.
  1379. Unregister from the hash_link. This must be done before freeing
  1380. the block. And it must be done if not freeing the block. Because
  1381. we could have waited above, we need to call remove_reader(). Other
  1382. threads could wait for us to release our request on the hash_link.
  1383. */
  1384. remove_reader(block);
  1385. /* If the block is not in eviction and not in free, we can free it. */
  1386. if (!(block->status &
  1387. (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH | BLOCK_REASSIGNED))) {
  1388. /*
  1389. Free block as we are going to write directly to file.
  1390. Although we have an exlusive lock for the updated key part,
  1391. the control can be yielded by the current thread as we might
  1392. have unfinished readers of other key parts in the block
  1393. buffer. Still we are guaranteed not to have any readers
  1394. of the key part we are writing into until the block is
  1395. removed from the cache as we set the BLOCK_REASSIGNED
  1396. flag (see the code below that handles reading requests).
  1397. */
  1398. free_block(keycache, thread, block);
  1399. } else {
  1400. /*
  1401. The block will be evicted/freed soon. Don't touch it in any way.
  1402. Unregister the request that we registered above.
  1403. */
  1404. unreg_request(keycache, block, 1);
  1405. /*
  1406. The block is still assigned to the hash_link (the file/pos that
  1407. we are going to write to). Wait until the eviction/free is
  1408. complete. Otherwise the direct write could complete before all
  1409. readers are done with the block. So they could read outdated
  1410. data.
  1411. Since we released our request on the hash_link, it can be reused
  1412. for another file/pos. Hence we cannot just check for
  1413. block->hash_link == hash_link. As long as the resize is
  1414. proceeding the block cannot be reassigned to the same file/pos
  1415. again. So we can terminate the loop when the block is no longer
  1416. assigned to this file/pos.
  1417. */
  1418. do {
  1419. wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock,
  1420. thread);
  1421. /*
  1422. If the flush phase failed, the resize could have finished
  1423. while we waited here.
  1424. */
  1425. if (!keycache->in_resize) goto restart;
  1426. } while (block->hash_link && (block->hash_link->file == file) &&
  1427. (block->hash_link->diskpos == filepos));
  1428. }
  1429. DBUG_RETURN(0);
  1430. }
  1431. if (page_status == PAGE_READ &&
  1432. (block->status &
  1433. (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH | BLOCK_REASSIGNED))) {
  1434. /*
  1435. This is a request for a block to be removed from cache. The block
  1436. is assigned to this hash_link and contains valid data, but is
  1437. marked for eviction or to be freed. Possible reasons why it has
  1438. not yet been evicted/freed can be a flush before reassignment
  1439. (BLOCK_IN_SWITCH), readers of the block have not finished yet
  1440. (BLOCK_REASSIGNED), or the evicting thread did not yet awake after
  1441. the block has been selected for it (BLOCK_IN_EVICTION).
  1442. */
  1443. /*
  1444. Only reading requests can proceed until the old dirty page is flushed,
  1445. all others are to be suspended, then resubmitted
  1446. */
  1447. if (!wrmode && !(block->status & BLOCK_REASSIGNED)) {
  1448. /*
  1449. This is a read request and the block not yet reassigned. We can
  1450. register our request and proceed. This unlinks the block from
  1451. the LRU ring and protects it against eviction.
  1452. */
  1453. reg_requests(keycache, block, 1);
  1454. } else {
  1455. /*
  1456. Either this is a write request for a block that is in eviction
  1457. or in free. We must not use it any more. Instead we must evict
  1458. another block. But we cannot do this before the eviction/free is
  1459. done. Otherwise we would find the same hash_link + block again
  1460. and again.
  1461. Or this is a read request for a block in eviction/free that does
  1462. not require a flush, but waits for readers to finish with the
  1463. block. We do not read this block to let the eviction/free happen
  1464. as soon as possible. Again we must wait so that we don't find
  1465. the same hash_link + block again and again.
  1466. */
  1467. DBUG_ASSERT(hash_link->requests);
  1468. hash_link->requests--;
  1469. wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock,
  1470. thread);
  1471. /*
  1472. The block is no longer assigned to this hash_link.
  1473. Get another one.
  1474. */
  1475. goto restart;
  1476. }
  1477. } else {
  1478. /*
  1479. This is a request for a new block or for a block not to be removed.
  1480. Either
  1481. - block == NULL or
  1482. - block not assigned to this hash_link or
  1483. - block assigned but not yet read from file,
  1484. or
  1485. - block assigned with valid (changed or unchanged) data and
  1486. - it will not be reassigned/freed.
  1487. */
  1488. if (!block) {
  1489. /* No block is assigned to the hash_link yet. */
  1490. if (keycache->blocks_unused) {
  1491. if (keycache->free_block_list) {
  1492. /* There is a block in the free list. */
  1493. block = keycache->free_block_list;
  1494. keycache->free_block_list = block->next_used;
  1495. block->next_used = NULL;
  1496. } else {
  1497. size_t block_mem_offset;
  1498. /* There are some never used blocks, take first of them */
  1499. DBUG_ASSERT(keycache->blocks_used < (ulong)keycache->disk_blocks);
  1500. block = &keycache->block_root[keycache->blocks_used];
  1501. block_mem_offset =
  1502. ((size_t)keycache->blocks_used) * keycache->key_cache_block_size;
  1503. block->buffer = keycache->block_mem + block_mem_offset;
  1504. keycache->blocks_used++;
  1505. DBUG_ASSERT(!block->next_used);
  1506. }
  1507. DBUG_ASSERT(!block->prev_used);
  1508. DBUG_ASSERT(!block->next_changed);
  1509. DBUG_ASSERT(!block->prev_changed);
  1510. DBUG_ASSERT(!block->hash_link);
  1511. DBUG_ASSERT(!block->status);
  1512. DBUG_ASSERT(!block->requests);
  1513. keycache->blocks_unused--;
  1514. block->status = BLOCK_IN_USE;
  1515. block->length = 0;
  1516. block->offset = keycache->key_cache_block_size;
  1517. block->requests = 1;
  1518. block->temperature = BLOCK_COLD;
  1519. block->hits_left = init_hits_left;
  1520. block->last_hit_time = 0;
  1521. block->hash_link = hash_link;
  1522. hash_link->block = block;
  1523. link_to_file_list(keycache, block, file, 0);
  1524. page_status = PAGE_TO_BE_READ;
  1525. } else {
  1526. /*
  1527. There are no free blocks and no never used blocks, use a block
  1528. from the LRU ring.
  1529. */
  1530. if (!keycache->used_last) {
  1531. /*
  1532. The LRU ring is empty. Wait until a new block is added to
  1533. it. Several threads might wait here for the same hash_link,
  1534. all of them must get the same block. While waiting for a
  1535. block, after a block is selected for this hash_link, other
  1536. threads can run first before this one awakes. During this
  1537. time interval other threads find this hash_link pointing to
  1538. the block, which is still assigned to another hash_link. In
  1539. this case the block is not marked BLOCK_IN_SWITCH yet, but
  1540. it is marked BLOCK_IN_EVICTION.
  1541. */
  1542. thread->opt_info = (void *)hash_link;
  1543. link_into_queue(&keycache->waiting_for_block, thread);
  1544. do {
  1545. mysql_cond_wait(&thread->suspend, &keycache->cache_lock);
  1546. } while (thread->next);
  1547. thread->opt_info = NULL;
  1548. /* Assert that block has a request registered. */
  1549. DBUG_ASSERT(hash_link->block->requests);
  1550. /* Assert that block is not in LRU ring. */
  1551. DBUG_ASSERT(!hash_link->block->next_used);
  1552. DBUG_ASSERT(!hash_link->block->prev_used);
  1553. }
  1554. /*
  1555. If we waited above, hash_link->block has been assigned by
  1556. link_block(). Otherwise it is still NULL. In the latter case
  1557. we need to grab a block from the LRU ring ourselves.
  1558. */
  1559. block = hash_link->block;
  1560. if (!block) {
  1561. /* Select the last block from the LRU ring. */
  1562. block = keycache->used_last->next_used;
  1563. block->hits_left = init_hits_left;
  1564. block->last_hit_time = 0;
  1565. hash_link->block = block;
  1566. /*
  1567. Register a request on the block. This unlinks it from the
  1568. LRU ring and protects it against eviction.
  1569. */
  1570. DBUG_ASSERT(!block->requests);
  1571. reg_requests(keycache, block, 1);
  1572. /*
  1573. We do not need to set block->status|= BLOCK_IN_EVICTION here
  1574. because we will set block->status|= BLOCK_IN_SWITCH
  1575. immediately without releasing the lock in between. This does
  1576. also support debugging. When looking at the block, one can
  1577. see if the block has been selected by link_block() after the
  1578. LRU ring was empty, or if it was grabbed directly from the
  1579. LRU ring in this branch.
  1580. */
  1581. }
  1582. /*
  1583. If we had to wait above, there is a small chance that another
  1584. thread grabbed this block for the same file block already. But
  1585. in most cases the first condition is true.
  1586. */
  1587. if (block->hash_link != hash_link &&
  1588. !(block->status & BLOCK_IN_SWITCH)) {
  1589. /* this is a primary request for a new page */
  1590. block->status |= BLOCK_IN_SWITCH;
  1591. if (block->status & BLOCK_CHANGED) {
  1592. /* The block contains a dirty page - push it out of the cache */
  1593. if (block->status & BLOCK_IN_FLUSH) {
  1594. /*
  1595. The block is marked for flush. If we do not wait here,
  1596. it could happen that we write the block, reassign it to
  1597. another file block, then, before the new owner can read
  1598. the new file block, the flusher writes the cache block
  1599. (which still has the old contents) to the new file block!
  1600. */
  1601. wait_on_queue(&block->wqueue[COND_FOR_SAVED],
  1602. &keycache->cache_lock, thread);
  1603. /*
  1604. The block is marked BLOCK_IN_SWITCH. It should be left
  1605. alone except for reading. No free, no write.
  1606. */
  1607. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1608. DBUG_ASSERT(!(block->status & (BLOCK_REASSIGNED | BLOCK_CHANGED |
  1609. BLOCK_FOR_UPDATE)));
  1610. } else {
  1611. block->status |= BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE;
  1612. /*
  1613. BLOCK_IN_EVICTION may be true or not. Other flags must
  1614. have a fixed value.
  1615. */
  1616. DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
  1617. (BLOCK_READ | BLOCK_IN_SWITCH | BLOCK_IN_FLUSH |
  1618. BLOCK_IN_FLUSHWRITE | BLOCK_CHANGED | BLOCK_IN_USE));
  1619. DBUG_ASSERT(block->hash_link);
  1620. mysql_mutex_unlock(&keycache->cache_lock);
  1621. /*
  1622. The call is thread safe because only the current
  1623. thread might change the block->hash_link value
  1624. */
  1625. error = (int)my_pwrite(block->hash_link->file,
  1626. block->buffer + block->offset,
  1627. block->length - block->offset,
  1628. block->hash_link->diskpos + block->offset,
  1629. MYF(MY_NABP | MY_WAIT_IF_FULL));
  1630. mysql_mutex_lock(&keycache->cache_lock);
  1631. /* Block status must not have changed. */
  1632. DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
  1633. (BLOCK_READ | BLOCK_IN_SWITCH | BLOCK_IN_FLUSH |
  1634. BLOCK_IN_FLUSHWRITE | BLOCK_CHANGED |
  1635. BLOCK_IN_USE) ||
  1636. fail_block(block));
  1637. keycache->global_cache_write++;
  1638. }
  1639. }
  1640. block->status |= BLOCK_REASSIGNED;
  1641. /*
  1642. The block comes from the LRU ring. It must have a hash_link
  1643. assigned.
  1644. */
  1645. DBUG_ASSERT(block->hash_link);
  1646. if (block->hash_link) {
  1647. /*
  1648. All pending requests for this page must be resubmitted.
  1649. This must be done before waiting for readers. They could
  1650. wait for the flush to complete. And we must also do it
  1651. after the wait. Flushers might try to free the block while
  1652. we wait. They would wait until the reassignment is
  1653. complete. Also the block status must reflect the correct
  1654. situation: The block is not changed nor in flush any more.
  1655. Note that we must not change the BLOCK_CHANGED flag
  1656. outside of link_to_file_list() so that it is always in the
  1657. correct queue and the *blocks_changed counters are
  1658. correct.
  1659. */
  1660. block->status &= ~(BLOCK_IN_FLUSH | BLOCK_IN_FLUSHWRITE);
  1661. link_to_file_list(keycache, block, block->hash_link->file, 1);
  1662. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  1663. /*
  1664. The block is still assigned to its old hash_link.
  1665. Wait until all pending read requests
  1666. for this page are executed
  1667. (we could have avoided this waiting, if we had read
  1668. a page in the cache in a sweep, without yielding control)
  1669. */
  1670. wait_for_readers(keycache, block, thread);
  1671. DBUG_ASSERT(block->hash_link && block->hash_link->block == block &&
  1672. block->prev_changed);
  1673. /* The reader must not have been a writer. */
  1674. DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
  1675. /* Wake flushers that might have found the block in between. */
  1676. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  1677. /* Remove the hash link for the old file block from the hash. */
  1678. unlink_hash(keycache, block->hash_link);
  1679. /*
  1680. For sanity checks link_to_file_list() asserts that block
  1681. and hash_link refer to each other. Hence we need to assign
  1682. the hash_link first, but then we would not know if it was
  1683. linked before. Hence we would not know if to unlink it. So
  1684. unlink it here and call link_to_file_list(..., false).
  1685. */
  1686. unlink_changed(block);
  1687. }
  1688. block->status = error ? BLOCK_ERROR : BLOCK_IN_USE;
  1689. block->length = 0;
  1690. block->offset = keycache->key_cache_block_size;
  1691. block->hash_link = hash_link;
  1692. link_to_file_list(keycache, block, file, 0);
  1693. page_status = PAGE_TO_BE_READ;
  1694. DBUG_ASSERT(block->hash_link->block == block);
  1695. DBUG_ASSERT(hash_link->block->hash_link == hash_link);
  1696. } else {
  1697. /*
  1698. Either (block->hash_link == hash_link),
  1699. or (block->status & BLOCK_IN_SWITCH).
  1700. This is for secondary requests for a new file block only.
  1701. Either it is already assigned to the new hash_link meanwhile
  1702. (if we had to wait due to empty LRU), or it is already in
  1703. eviction by another thread. Since this block has been
  1704. grabbed from the LRU ring and attached to this hash_link,
  1705. another thread cannot grab the same block from the LRU ring
  1706. anymore. If the block is in eviction already, it must become
  1707. attached to the same hash_link and as such destined for the
  1708. same file block.
  1709. */
  1710. page_status =
  1711. (((block->hash_link == hash_link) && (block->status & BLOCK_READ))
  1712. ? PAGE_READ
  1713. : PAGE_WAIT_TO_BE_READ);
  1714. }
  1715. }
  1716. } else {
  1717. /*
  1718. Block is not NULL. This hash_link points to a block.
  1719. Either
  1720. - block not assigned to this hash_link (yet) or
  1721. - block assigned but not yet read from file,
  1722. or
  1723. - block assigned with valid (changed or unchanged) data and
  1724. - it will not be reassigned/freed.
  1725. The first condition means hash_link points to a block in
  1726. eviction. This is not necessarily marked by BLOCK_IN_SWITCH yet.
  1727. But then it is marked BLOCK_IN_EVICTION. See the NOTE in
  1728. link_block(). In both cases it is destined for this hash_link
  1729. and its file block address. When this hash_link got its block
  1730. address, the block was removed from the LRU ring and cannot be
  1731. selected for eviction (for another hash_link) again.
  1732. Register a request on the block. This is another protection
  1733. against eviction.
  1734. */
  1735. DBUG_ASSERT(
  1736. ((block->hash_link != hash_link) &&
  1737. (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) ||
  1738. ((block->hash_link == hash_link) && !(block->status & BLOCK_READ)) ||
  1739. ((block->status & BLOCK_READ) &&
  1740. !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))));
  1741. reg_requests(keycache, block, 1);
  1742. page_status =
  1743. (((block->hash_link == hash_link) && (block->status & BLOCK_READ))
  1744. ? PAGE_READ
  1745. : PAGE_WAIT_TO_BE_READ);
  1746. }
  1747. }
  1748. DBUG_ASSERT(page_status != -1);
  1749. /* Same assert basically, but be very sure. */
  1750. DBUG_ASSERT(block);
  1751. /* Assert that block has a request and is not in LRU ring. */
  1752. DBUG_ASSERT(block->requests);
  1753. DBUG_ASSERT(!block->next_used);
  1754. DBUG_ASSERT(!block->prev_used);
  1755. /* Assert that we return the correct block. */
  1756. DBUG_ASSERT((page_status == PAGE_WAIT_TO_BE_READ) ||
  1757. ((block->hash_link->file == file) &&
  1758. (block->hash_link->diskpos == filepos)));
  1759. *page_st = page_status;
  1760. DBUG_RETURN(block);
  1761. }
  1762. /*
  1763. Read into a key cache block buffer from disk.
  1764. SYNOPSIS
  1765. read_block()
  1766. keycache pointer to a key cache data structure
  1767. thread_var pointer to thread specific variables
  1768. block block to which buffer the data is to be read
  1769. read_length size of data to be read
  1770. min_length at least so much data must be read
  1771. primary <-> the current thread will read the data
  1772. RETURN VALUE
  1773. None
  1774. NOTES.
  1775. The function either reads a page data from file to the block buffer,
  1776. or waits until another thread reads it. What page to read is determined
  1777. by a block parameter - reference to a hash link for this page.
  1778. If an error occurs THE BLOCK_ERROR bit is set in the block status.
  1779. We do not report error when the size of successfully read
  1780. portion is less than read_length, but not less than min_length.
  1781. */
  1782. static void read_block(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  1783. BLOCK_LINK *block, uint read_length, uint min_length,
  1784. bool primary) {
  1785. size_t got_length;
  1786. /* On entry cache_lock is locked */
  1787. if (primary) {
  1788. /*
  1789. This code is executed only by threads that submitted primary
  1790. requests. Until block->status contains BLOCK_READ, all other
  1791. request for the block become secondary requests. For a primary
  1792. request the block must be properly initialized.
  1793. */
  1794. DBUG_ASSERT(((block->status & ~BLOCK_FOR_UPDATE) == BLOCK_IN_USE) ||
  1795. fail_block(block));
  1796. DBUG_ASSERT((block->length == 0) || fail_block(block));
  1797. DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
  1798. fail_block(block));
  1799. DBUG_ASSERT((block->requests > 0) || fail_block(block));
  1800. keycache->global_cache_read++;
  1801. /* Page is not in buffer yet, is to be read from disk */
  1802. mysql_mutex_unlock(&keycache->cache_lock);
  1803. /*
  1804. Here other threads may step in and register as secondary readers.
  1805. They will register in block->wqueue[COND_FOR_REQUESTED].
  1806. */
  1807. got_length = my_pread(block->hash_link->file, block->buffer, read_length,
  1808. block->hash_link->diskpos, MYF(0));
  1809. mysql_mutex_lock(&keycache->cache_lock);
  1810. /*
  1811. The block can now have been marked for free (in case of
  1812. FLUSH_RELEASE). Otherwise the state must be unchanged.
  1813. */
  1814. DBUG_ASSERT(((block->status & ~(BLOCK_REASSIGNED | BLOCK_FOR_UPDATE)) ==
  1815. BLOCK_IN_USE) ||
  1816. fail_block(block));
  1817. DBUG_ASSERT((block->length == 0) || fail_block(block));
  1818. DBUG_ASSERT((block->offset == keycache->key_cache_block_size) ||
  1819. fail_block(block));
  1820. DBUG_ASSERT((block->requests > 0) || fail_block(block));
  1821. if (got_length < min_length)
  1822. block->status |= BLOCK_ERROR;
  1823. else {
  1824. block->status |= BLOCK_READ;
  1825. block->length = (int)got_length;
  1826. /*
  1827. Do not set block->offset here. If this block is marked
  1828. BLOCK_CHANGED later, we want to flush only the modified part. So
  1829. only a writer may set block->offset down from
  1830. keycache->key_cache_block_size.
  1831. */
  1832. }
  1833. /* Signal that all pending requests for this page now can be processed */
  1834. release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
  1835. } else {
  1836. /*
  1837. This code is executed only by threads that submitted secondary
  1838. requests. At this point it could happen that the cache block is
  1839. not yet assigned to the hash_link for the requested file block.
  1840. But at awake from the wait this should be the case. Unfortunately
  1841. we cannot assert this here because we do not know the hash_link
  1842. for the requested file block nor the file and position. So we have
  1843. to assert this in the caller.
  1844. */
  1845. wait_on_queue(&block->wqueue[COND_FOR_REQUESTED], &keycache->cache_lock,
  1846. thread_var);
  1847. }
  1848. }
  1849. /*
  1850. Read a block of data from a cached file into a buffer;
  1851. SYNOPSIS
  1852. key_cache_read()
  1853. keycache pointer to a key cache data structure
  1854. thread_var pointer to thread specific variables
  1855. file handler for the file for the block of data to be read
  1856. filepos position of the block of data in the file
  1857. level determines the weight of the data
  1858. buff buffer to where the data must be placed
  1859. length length of the buffer
  1860. block_length length of the block in the key cache buffer
  1861. return_buffer return pointer to the key cache buffer with the data
  1862. RETURN VALUE
  1863. Returns address from where the data is placed if sucessful, 0 - otherwise.
  1864. NOTES.
  1865. The function ensures that a block of data of size length from file
  1866. positioned at filepos is in the buffers for some key cache blocks.
  1867. Then the function either copies the data into the buffer buff, or,
  1868. if return_buffer is true, it just returns the pointer to the key cache
  1869. buffer with the data.
  1870. Filepos must be a multiple of 'block_length', but it doesn't
  1871. have to be a multiple of key_cache_block_size;
  1872. */
  1873. uchar *key_cache_read(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  1874. File file, my_off_t filepos, int level, uchar *buff,
  1875. uint length, uint block_length,
  1876. int return_buffer MY_ATTRIBUTE((unused))) {
  1877. bool locked_and_incremented = false;
  1878. int error = 0;
  1879. uchar *start = buff;
  1880. DBUG_ENTER("key_cache_read");
  1881. DBUG_PRINT("enter", ("fd: %u pos: %lu length: %u", (uint)file,
  1882. (ulong)filepos, length));
  1883. if (keycache->key_cache_inited) {
  1884. /* Key cache is used */
  1885. BLOCK_LINK *block;
  1886. uint read_length;
  1887. uint offset;
  1888. int page_st;
  1889. /*
  1890. When the key cache is once initialized, we use the cache_lock to
  1891. reliably distinguish the cases of normal operation, resizing, and
  1892. disabled cache. We always increment and decrement
  1893. 'cnt_for_resize_op' so that a resizer can wait for pending I/O.
  1894. */
  1895. mysql_mutex_lock(&keycache->cache_lock);
  1896. /*
  1897. Cache resizing has two phases: Flushing and re-initializing. In
  1898. the flush phase read requests are allowed to bypass the cache for
  1899. blocks not in the cache. find_key_block() returns NULL in this
  1900. case.
  1901. After the flush phase new I/O requests must wait until the
  1902. re-initialization is done. The re-initialization can be done only
  1903. if no I/O request is in progress. The reason is that
  1904. key_cache_block_size can change. With enabled cache, I/O is done
  1905. in chunks of key_cache_block_size. Every chunk tries to use a
  1906. cache block first. If the block size changes in the middle, a
  1907. block could be missed and old data could be read.
  1908. */
  1909. while (keycache->in_resize && !keycache->resize_in_flush)
  1910. wait_on_queue(&keycache->resize_queue, &keycache->cache_lock, thread_var);
  1911. /* Register the I/O for the next resize. */
  1912. inc_counter_for_resize_op(keycache);
  1913. locked_and_incremented = true;
  1914. /* Requested data may not always be aligned to cache blocks. */
  1915. offset = (uint)(filepos % keycache->key_cache_block_size);
  1916. /* Read data in key_cache_block_size increments */
  1917. do {
  1918. /* Cache could be disabled in a later iteration. */
  1919. if (!keycache->can_be_used) {
  1920. goto no_key_cache;
  1921. }
  1922. /* Start reading at the beginning of the cache block. */
  1923. filepos -= offset;
  1924. /* Do not read beyond the end of the cache block. */
  1925. read_length = length;
  1926. set_if_smaller(read_length, keycache->key_cache_block_size - offset);
  1927. DBUG_ASSERT(read_length > 0);
  1928. if (block_length > keycache->key_cache_block_size || offset)
  1929. return_buffer = 0;
  1930. /* Request the cache block that matches file/pos. */
  1931. keycache->global_cache_r_requests++;
  1932. block = find_key_block(keycache, thread_var, file, filepos, level, 0,
  1933. &page_st);
  1934. if (!block) {
  1935. /*
  1936. This happens only for requests submitted during key cache
  1937. resize. The block is not in the cache and shall not go in.
  1938. Read directly from file.
  1939. */
  1940. keycache->global_cache_read++;
  1941. mysql_mutex_unlock(&keycache->cache_lock);
  1942. error = (my_pread(file, (uchar *)buff, read_length, filepos + offset,
  1943. MYF(MY_NABP)) != 0);
  1944. mysql_mutex_lock(&keycache->cache_lock);
  1945. goto next_block;
  1946. }
  1947. if (!(block->status & BLOCK_ERROR)) {
  1948. if (page_st != PAGE_READ) {
  1949. /* The requested page is to be read into the block buffer */
  1950. read_block(keycache, thread_var, block,
  1951. keycache->key_cache_block_size, read_length + offset,
  1952. page_st == PAGE_TO_BE_READ);
  1953. /*
  1954. A secondary request must now have the block assigned to the
  1955. requested file block. It does not hurt to check it for
  1956. primary requests too.
  1957. */
  1958. DBUG_ASSERT(keycache->can_be_used);
  1959. DBUG_ASSERT(block->hash_link->file == file);
  1960. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  1961. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1962. } else if (block->length < read_length + offset) {
  1963. /*
  1964. Impossible if nothing goes wrong:
  1965. this could only happen if we are using a file with
  1966. small key blocks and are trying to read outside the file
  1967. */
  1968. set_my_errno(-1);
  1969. block->status |= BLOCK_ERROR;
  1970. }
  1971. }
  1972. /* block status may have added BLOCK_ERROR in the above 'if'. */
  1973. if (!(block->status & BLOCK_ERROR)) {
  1974. {
  1975. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1976. mysql_mutex_unlock(&keycache->cache_lock);
  1977. /* Copy data from the cache buffer */
  1978. memcpy(buff, block->buffer + offset, (size_t)read_length);
  1979. mysql_mutex_lock(&keycache->cache_lock);
  1980. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  1981. }
  1982. }
  1983. remove_reader(block);
  1984. /* Error injection for coverage testing. */
  1985. DBUG_EXECUTE_IF("key_cache_read_block_error",
  1986. block->status |= BLOCK_ERROR;);
  1987. /* Do not link erroneous blocks into the LRU ring, but free them. */
  1988. if (!(block->status & BLOCK_ERROR)) {
  1989. /*
  1990. Link the block into the LRU ring if it's the last submitted
  1991. request for the block. This enables eviction for the block.
  1992. */
  1993. unreg_request(keycache, block, 1);
  1994. } else {
  1995. free_block(keycache, thread_var, block);
  1996. error = 1;
  1997. break;
  1998. }
  1999. next_block:
  2000. buff += read_length;
  2001. filepos += read_length + offset;
  2002. offset = 0;
  2003. } while ((length -= read_length));
  2004. goto end;
  2005. }
  2006. no_key_cache:
  2007. /* Key cache is not used */
  2008. keycache->global_cache_r_requests++;
  2009. keycache->global_cache_read++;
  2010. if (locked_and_incremented) mysql_mutex_unlock(&keycache->cache_lock);
  2011. if (my_pread(file, (uchar *)buff, length, filepos, MYF(MY_NABP))) error = 1;
  2012. if (locked_and_incremented) mysql_mutex_lock(&keycache->cache_lock);
  2013. end:
  2014. if (locked_and_incremented) {
  2015. dec_counter_for_resize_op(keycache);
  2016. mysql_mutex_unlock(&keycache->cache_lock);
  2017. }
  2018. DBUG_PRINT("exit", ("error: %d", error));
  2019. DBUG_RETURN(error ? (uchar *)0 : start);
  2020. }
  2021. /*
  2022. Insert a block of file data from a buffer into key cache
  2023. SYNOPSIS
  2024. key_cache_insert()
  2025. keycache pointer to a key cache data structure
  2026. thread_var pointer to thread specific variables
  2027. file handler for the file to insert data from
  2028. filepos position of the block of data in the file to insert
  2029. level determines the weight of the data
  2030. buff buffer to read data from
  2031. length length of the data in the buffer
  2032. NOTES
  2033. This is used by MyISAM to move all blocks from a index file to the key
  2034. cache
  2035. RETURN VALUE
  2036. 0 if a success, 1 - otherwise.
  2037. */
  2038. int key_cache_insert(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  2039. File file, my_off_t filepos, int level, uchar *buff,
  2040. uint length) {
  2041. int error = 0;
  2042. DBUG_ENTER("key_cache_insert");
  2043. DBUG_PRINT("enter", ("fd: %u pos: %lu length: %u", (uint)file,
  2044. (ulong)filepos, length));
  2045. if (keycache->key_cache_inited) {
  2046. /* Key cache is used */
  2047. BLOCK_LINK *block;
  2048. uint read_length;
  2049. uint offset;
  2050. int page_st;
  2051. bool locked_and_incremented = false;
  2052. /*
  2053. When the keycache is once initialized, we use the cache_lock to
  2054. reliably distinguish the cases of normal operation, resizing, and
  2055. disabled cache. We always increment and decrement
  2056. 'cnt_for_resize_op' so that a resizer can wait for pending I/O.
  2057. */
  2058. mysql_mutex_lock(&keycache->cache_lock);
  2059. /*
  2060. We do not load index data into a disabled cache nor into an
  2061. ongoing resize.
  2062. */
  2063. if (!keycache->can_be_used || keycache->in_resize) goto no_key_cache;
  2064. /* Register the pseudo I/O for the next resize. */
  2065. inc_counter_for_resize_op(keycache);
  2066. locked_and_incremented = true;
  2067. /* Loaded data may not always be aligned to cache blocks. */
  2068. offset = (uint)(filepos % keycache->key_cache_block_size);
  2069. /* Load data in key_cache_block_size increments. */
  2070. do {
  2071. /* Cache could be disabled or resizing in a later iteration. */
  2072. if (!keycache->can_be_used || keycache->in_resize) goto no_key_cache;
  2073. /* Start loading at the beginning of the cache block. */
  2074. filepos -= offset;
  2075. /* Do not load beyond the end of the cache block. */
  2076. read_length = length;
  2077. set_if_smaller(read_length, keycache->key_cache_block_size - offset);
  2078. DBUG_ASSERT(read_length > 0);
  2079. /* The block has been read by the caller already. */
  2080. keycache->global_cache_read++;
  2081. /* Request the cache block that matches file/pos. */
  2082. keycache->global_cache_r_requests++;
  2083. block = find_key_block(keycache, thread_var, file, filepos, level, 0,
  2084. &page_st);
  2085. if (!block) {
  2086. /*
  2087. This happens only for requests submitted during key cache
  2088. resize. The block is not in the cache and shall not go in.
  2089. Stop loading index data.
  2090. */
  2091. goto no_key_cache;
  2092. }
  2093. if (!(block->status & BLOCK_ERROR)) {
  2094. if ((page_st == PAGE_WAIT_TO_BE_READ) ||
  2095. ((page_st == PAGE_TO_BE_READ) &&
  2096. (offset || (read_length < keycache->key_cache_block_size)))) {
  2097. /*
  2098. Either
  2099. this is a secondary request for a block to be read into the
  2100. cache. The block is in eviction. It is not yet assigned to
  2101. the requested file block (It does not point to the right
  2102. hash_link). So we cannot call remove_reader() on the block.
  2103. And we cannot access the hash_link directly here. We need to
  2104. wait until the assignment is complete. read_block() executes
  2105. the correct wait when called with primary == false.
  2106. Or
  2107. this is a primary request for a block to be read into the
  2108. cache and the supplied data does not fill the whole block.
  2109. This function is called on behalf of a LOAD INDEX INTO CACHE
  2110. statement, which is a read-only task and allows other
  2111. readers. It is possible that a parallel running reader tries
  2112. to access this block. If it needs more data than has been
  2113. supplied here, it would report an error. To be sure that we
  2114. have all data in the block that is available in the file, we
  2115. read the block ourselves.
  2116. Though reading again what the caller did read already is an
  2117. expensive operation, we need to do this for correctness.
  2118. */
  2119. read_block(keycache, thread_var, block,
  2120. keycache->key_cache_block_size, read_length + offset,
  2121. (page_st == PAGE_TO_BE_READ));
  2122. /*
  2123. A secondary request must now have the block assigned to the
  2124. requested file block. It does not hurt to check it for
  2125. primary requests too.
  2126. */
  2127. DBUG_ASSERT(keycache->can_be_used);
  2128. DBUG_ASSERT(block->hash_link->file == file);
  2129. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  2130. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2131. } else if (page_st == PAGE_TO_BE_READ) {
  2132. /*
  2133. This is a new block in the cache. If we come here, we have
  2134. data for the whole block.
  2135. */
  2136. DBUG_ASSERT(block->hash_link->requests);
  2137. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  2138. DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
  2139. (block->status & BLOCK_READ));
  2140. mysql_mutex_unlock(&keycache->cache_lock);
  2141. /*
  2142. Here other threads may step in and register as secondary readers.
  2143. They will register in block->wqueue[COND_FOR_REQUESTED].
  2144. */
  2145. /* Copy data from buff */
  2146. memcpy(block->buffer + offset, buff, (size_t)read_length);
  2147. mysql_mutex_lock(&keycache->cache_lock);
  2148. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  2149. DBUG_ASSERT((page_st == PAGE_TO_BE_READ) ||
  2150. (block->status & BLOCK_READ));
  2151. /*
  2152. After the data is in the buffer, we can declare the block
  2153. valid. Now other threads do not need to register as
  2154. secondary readers any more. They can immediately access the
  2155. block.
  2156. */
  2157. block->status |= BLOCK_READ;
  2158. block->length = read_length + offset;
  2159. /*
  2160. Do not set block->offset here. If this block is marked
  2161. BLOCK_CHANGED later, we want to flush only the modified part. So
  2162. only a writer may set block->offset down from
  2163. keycache->key_cache_block_size.
  2164. */
  2165. /* Signal all pending requests. */
  2166. release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
  2167. } else {
  2168. /*
  2169. page_st == PAGE_READ. The block is in the buffer. All data
  2170. must already be present. Blocks are always read with all
  2171. data available on file. Assert that the block does not have
  2172. less contents than the preloader supplies. If the caller has
  2173. data beyond block->length, it means that a file write has
  2174. been done while this block was in cache and not extended
  2175. with the new data. If the condition is met, we can simply
  2176. ignore the block.
  2177. */
  2178. DBUG_ASSERT((page_st == PAGE_READ) &&
  2179. (read_length + offset <= block->length));
  2180. }
  2181. /*
  2182. A secondary request must now have the block assigned to the
  2183. requested file block. It does not hurt to check it for primary
  2184. requests too.
  2185. */
  2186. DBUG_ASSERT(block->hash_link->file == file);
  2187. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  2188. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2189. } /* end of if (!(block->status & BLOCK_ERROR)) */
  2190. remove_reader(block);
  2191. /* Error injection for coverage testing. */
  2192. DBUG_EXECUTE_IF("key_cache_insert_block_error",
  2193. block->status |= BLOCK_ERROR;
  2194. errno = EIO;);
  2195. /* Do not link erroneous blocks into the LRU ring, but free them. */
  2196. if (!(block->status & BLOCK_ERROR)) {
  2197. /*
  2198. Link the block into the LRU ring if it's the last submitted
  2199. request for the block. This enables eviction for the block.
  2200. */
  2201. unreg_request(keycache, block, 1);
  2202. } else {
  2203. free_block(keycache, thread_var, block);
  2204. error = 1;
  2205. break;
  2206. }
  2207. buff += read_length;
  2208. filepos += read_length + offset;
  2209. offset = 0;
  2210. } while ((length -= read_length));
  2211. no_key_cache:
  2212. if (locked_and_incremented) dec_counter_for_resize_op(keycache);
  2213. mysql_mutex_unlock(&keycache->cache_lock);
  2214. }
  2215. DBUG_RETURN(error);
  2216. }
  2217. /*
  2218. Write a buffer into a cached file.
  2219. SYNOPSIS
  2220. key_cache_write()
  2221. keycache pointer to a key cache data structure
  2222. thread_var pointer to thread specific variables
  2223. file handler for the file to write data to
  2224. filepos position in the file to write data to
  2225. level determines the weight of the data
  2226. buff buffer with the data
  2227. length length of the buffer
  2228. dont_write if is 0 then all dirty pages involved in writing
  2229. should have been flushed from key cache
  2230. RETURN VALUE
  2231. 0 if a success, 1 - otherwise.
  2232. NOTES.
  2233. The function copies the data of size length from buff into buffers
  2234. for key cache blocks that are assigned to contain the portion of
  2235. the file starting with position filepos.
  2236. It ensures that this data is flushed to the file if dont_write is false.
  2237. Filepos must be a multiple of 'block_length', but it doesn't
  2238. have to be a multiple of key_cache_block_size;
  2239. dont_write is always true in the server (info->lock_type is never F_UNLCK).
  2240. */
  2241. int key_cache_write(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  2242. File file, my_off_t filepos, int level, uchar *buff,
  2243. uint length, uint block_length MY_ATTRIBUTE((unused)),
  2244. int dont_write) {
  2245. bool locked_and_incremented = false;
  2246. int error = 0;
  2247. DBUG_ENTER("key_cache_write");
  2248. DBUG_PRINT("enter", ("fd: %u pos: %lu length: %u block_length: %u"
  2249. " key_block_length: %u",
  2250. (uint)file, (ulong)filepos, length, block_length,
  2251. keycache ? keycache->key_cache_block_size : 0));
  2252. if (!dont_write) {
  2253. /* purecov: begin inspected */
  2254. /* Not used in the server. */
  2255. /* Force writing from buff into disk. */
  2256. keycache->global_cache_w_requests++;
  2257. keycache->global_cache_write++;
  2258. if (my_pwrite(file, buff, length, filepos, MYF(MY_NABP | MY_WAIT_IF_FULL)))
  2259. DBUG_RETURN(1);
  2260. /* purecov: end */
  2261. }
  2262. if (keycache->key_cache_inited) {
  2263. /* Key cache is used */
  2264. BLOCK_LINK *block;
  2265. uint read_length;
  2266. uint offset;
  2267. int page_st;
  2268. /*
  2269. When the key cache is once initialized, we use the cache_lock to
  2270. reliably distinguish the cases of normal operation, resizing, and
  2271. disabled cache. We always increment and decrement
  2272. 'cnt_for_resize_op' so that a resizer can wait for pending I/O.
  2273. */
  2274. mysql_mutex_lock(&keycache->cache_lock);
  2275. /*
  2276. Cache resizing has two phases: Flushing and re-initializing. In
  2277. the flush phase write requests can modify dirty blocks that are
  2278. not yet in flush. Otherwise they are allowed to bypass the cache.
  2279. find_key_block() returns NULL in both cases (clean blocks and
  2280. non-cached blocks).
  2281. After the flush phase new I/O requests must wait until the
  2282. re-initialization is done. The re-initialization can be done only
  2283. if no I/O request is in progress. The reason is that
  2284. key_cache_block_size can change. With enabled cache I/O is done in
  2285. chunks of key_cache_block_size. Every chunk tries to use a cache
  2286. block first. If the block size changes in the middle, a block
  2287. could be missed and data could be written below a cached block.
  2288. */
  2289. while (keycache->in_resize && !keycache->resize_in_flush)
  2290. wait_on_queue(&keycache->resize_queue, &keycache->cache_lock, thread_var);
  2291. /* Register the I/O for the next resize. */
  2292. inc_counter_for_resize_op(keycache);
  2293. locked_and_incremented = true;
  2294. /* Requested data may not always be aligned to cache blocks. */
  2295. offset = (uint)(filepos % keycache->key_cache_block_size);
  2296. /* Write data in key_cache_block_size increments. */
  2297. do {
  2298. /* Cache could be disabled in a later iteration. */
  2299. if (!keycache->can_be_used) goto no_key_cache;
  2300. /* Start writing at the beginning of the cache block. */
  2301. filepos -= offset;
  2302. /* Do not write beyond the end of the cache block. */
  2303. read_length = length;
  2304. set_if_smaller(read_length, keycache->key_cache_block_size - offset);
  2305. DBUG_ASSERT(read_length > 0);
  2306. /* Request the cache block that matches file/pos. */
  2307. keycache->global_cache_w_requests++;
  2308. block = find_key_block(keycache, thread_var, file, filepos, level, 1,
  2309. &page_st);
  2310. if (!block) {
  2311. /*
  2312. This happens only for requests submitted during key cache
  2313. resize. The block is not in the cache and shall not go in.
  2314. Write directly to file.
  2315. */
  2316. if (dont_write) {
  2317. /* Used in the server. */
  2318. keycache->global_cache_write++;
  2319. mysql_mutex_unlock(&keycache->cache_lock);
  2320. if (my_pwrite(file, (uchar *)buff, read_length, filepos + offset,
  2321. MYF(MY_NABP | MY_WAIT_IF_FULL)))
  2322. error = 1;
  2323. mysql_mutex_lock(&keycache->cache_lock);
  2324. }
  2325. goto next_block;
  2326. }
  2327. /*
  2328. Prevent block from flushing and from being selected for to be
  2329. freed. This must be set when we release the cache_lock.
  2330. However, we must not set the status of the block before it is
  2331. assigned to this file/pos.
  2332. */
  2333. if (page_st != PAGE_WAIT_TO_BE_READ) block->status |= BLOCK_FOR_UPDATE;
  2334. /*
  2335. We must read the file block first if it is not yet in the cache
  2336. and we do not replace all of its contents.
  2337. In cases where the cache block is big enough to contain (parts
  2338. of) index blocks of different indexes, our request can be
  2339. secondary (PAGE_WAIT_TO_BE_READ). In this case another thread is
  2340. reading the file block. If the read completes after us, it
  2341. overwrites our new contents with the old contents. So we have to
  2342. wait for the other thread to complete the read of this block.
  2343. read_block() takes care for the wait.
  2344. */
  2345. if (!(block->status & BLOCK_ERROR) &&
  2346. ((page_st == PAGE_TO_BE_READ &&
  2347. (offset || read_length < keycache->key_cache_block_size)) ||
  2348. (page_st == PAGE_WAIT_TO_BE_READ))) {
  2349. read_block(keycache, thread_var, block,
  2350. offset + read_length >= keycache->key_cache_block_size
  2351. ? offset
  2352. : keycache->key_cache_block_size,
  2353. offset, (page_st == PAGE_TO_BE_READ));
  2354. DBUG_ASSERT(keycache->can_be_used);
  2355. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2356. /*
  2357. Prevent block from flushing and from being selected for to be
  2358. freed. This must be set when we release the cache_lock.
  2359. Here we set it in case we could not set it above.
  2360. */
  2361. block->status |= BLOCK_FOR_UPDATE;
  2362. }
  2363. /*
  2364. The block should always be assigned to the requested file block
  2365. here. It need not be BLOCK_READ when overwriting the whole block.
  2366. */
  2367. DBUG_ASSERT(block->hash_link->file == file);
  2368. DBUG_ASSERT(block->hash_link->diskpos == filepos);
  2369. DBUG_ASSERT(block->status & BLOCK_IN_USE);
  2370. DBUG_ASSERT((page_st == PAGE_TO_BE_READ) || (block->status & BLOCK_READ));
  2371. /*
  2372. The block to be written must not be marked BLOCK_REASSIGNED.
  2373. Otherwise it could be freed in dirty state or reused without
  2374. another flush during eviction. It must also not be in flush.
  2375. Otherwise the old contens may have been flushed already and
  2376. the flusher could clear BLOCK_CHANGED without flushing the
  2377. new changes again.
  2378. */
  2379. DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
  2380. while (block->status & BLOCK_IN_FLUSHWRITE) {
  2381. /*
  2382. Another thread is flushing the block. It was dirty already.
  2383. Wait until the block is flushed to file. Otherwise we could
  2384. modify the buffer contents just while it is written to file.
  2385. An unpredictable file block contents would be the result.
  2386. While we wait, several things can happen to the block,
  2387. including another flush. But the block cannot be reassigned to
  2388. another hash_link until we release our request on it.
  2389. */
  2390. wait_on_queue(&block->wqueue[COND_FOR_SAVED], &keycache->cache_lock,
  2391. thread_var);
  2392. DBUG_ASSERT(keycache->can_be_used);
  2393. DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
  2394. /* Still must not be marked for free. */
  2395. DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
  2396. DBUG_ASSERT(block->hash_link && (block->hash_link->block == block));
  2397. }
  2398. /*
  2399. We could perhaps release the cache_lock during access of the
  2400. data like in the other functions. Locks outside of the key cache
  2401. assure that readers and a writer do not access the same range of
  2402. data. Parallel accesses should happen only if the cache block
  2403. contains multiple index block(fragment)s. So different parts of
  2404. the buffer would be read/written. An attempt to flush during
  2405. memcpy() is prevented with BLOCK_FOR_UPDATE.
  2406. */
  2407. if (!(block->status & BLOCK_ERROR)) {
  2408. mysql_mutex_unlock(&keycache->cache_lock);
  2409. memcpy(block->buffer + offset, buff, (size_t)read_length);
  2410. mysql_mutex_lock(&keycache->cache_lock);
  2411. }
  2412. if (!dont_write) {
  2413. /* Not used in the server. buff has been written to disk at start. */
  2414. if ((block->status & BLOCK_CHANGED) &&
  2415. (!offset && read_length >= keycache->key_cache_block_size))
  2416. link_to_file_list(keycache, block, block->hash_link->file, 1);
  2417. } else if (!(block->status & BLOCK_CHANGED))
  2418. link_to_changed_list(keycache, block);
  2419. block->status |= BLOCK_READ;
  2420. /*
  2421. Allow block to be selected for to be freed. Since it is marked
  2422. BLOCK_CHANGED too, it won't be selected for to be freed without
  2423. a flush.
  2424. */
  2425. block->status &= ~BLOCK_FOR_UPDATE;
  2426. set_if_smaller(block->offset, offset);
  2427. set_if_bigger(block->length, read_length + offset);
  2428. /* Threads may be waiting for the changes to be complete. */
  2429. release_whole_queue(&block->wqueue[COND_FOR_REQUESTED]);
  2430. /*
  2431. If only a part of the cache block is to be replaced, and the
  2432. rest has been read from file, then the cache lock has been
  2433. released for I/O and it could be possible that another thread
  2434. wants to evict or free the block and waits for it to be
  2435. released. So we must not just decrement hash_link->requests, but
  2436. also wake a waiting thread.
  2437. */
  2438. remove_reader(block);
  2439. /* Error injection for coverage testing. */
  2440. DBUG_EXECUTE_IF("key_cache_write_block_error",
  2441. block->status |= BLOCK_ERROR;);
  2442. /* Do not link erroneous blocks into the LRU ring, but free them. */
  2443. if (!(block->status & BLOCK_ERROR)) {
  2444. /*
  2445. Link the block into the LRU ring if it's the last submitted
  2446. request for the block. This enables eviction for the block.
  2447. */
  2448. unreg_request(keycache, block, 1);
  2449. } else {
  2450. /* Pretend a "clean" block to avoid complications. */
  2451. block->status &= ~(BLOCK_CHANGED);
  2452. free_block(keycache, thread_var, block);
  2453. error = 1;
  2454. break;
  2455. }
  2456. next_block:
  2457. buff += read_length;
  2458. filepos += read_length + offset;
  2459. offset = 0;
  2460. } while ((length -= read_length));
  2461. goto end;
  2462. }
  2463. no_key_cache:
  2464. /* Key cache is not used */
  2465. if (dont_write) {
  2466. /* Used in the server. */
  2467. keycache->global_cache_w_requests++;
  2468. keycache->global_cache_write++;
  2469. if (locked_and_incremented) mysql_mutex_unlock(&keycache->cache_lock);
  2470. if (my_pwrite(file, (uchar *)buff, length, filepos,
  2471. MYF(MY_NABP | MY_WAIT_IF_FULL)))
  2472. error = 1;
  2473. if (locked_and_incremented) mysql_mutex_lock(&keycache->cache_lock);
  2474. }
  2475. end:
  2476. if (locked_and_incremented) {
  2477. dec_counter_for_resize_op(keycache);
  2478. mysql_mutex_unlock(&keycache->cache_lock);
  2479. }
  2480. DBUG_RETURN(error);
  2481. }
  2482. /*
  2483. Free block.
  2484. SYNOPSIS
  2485. free_block()
  2486. keycache Pointer to a key cache data structure
  2487. thread_var Pointer to thread specific variables
  2488. block Pointer to the block to free
  2489. DESCRIPTION
  2490. Remove reference to block from hash table.
  2491. Remove block from the chain of clean blocks.
  2492. Add block to the free list.
  2493. NOTE
  2494. Block must not be free (status == 0).
  2495. Block must not be in free_block_list.
  2496. Block must not be in the LRU ring.
  2497. Block must not be in eviction (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH).
  2498. Block must not be in free (BLOCK_REASSIGNED).
  2499. Block must not be in flush (BLOCK_IN_FLUSH).
  2500. Block must not be dirty (BLOCK_CHANGED).
  2501. Block must not be in changed_blocks (dirty) hash.
  2502. Block must be in file_blocks (clean) hash.
  2503. Block must refer to a hash_link.
  2504. Block must have a request registered on it.
  2505. */
  2506. static void free_block(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  2507. BLOCK_LINK *block) {
  2508. /*
  2509. Assert that the block is not free already. And that it is in a clean
  2510. state. Note that the block might just be assigned to a hash_link and
  2511. not yet read (BLOCK_READ may not be set here). In this case a reader
  2512. is registered in the hash_link and free_block() will wait for it
  2513. below.
  2514. */
  2515. DBUG_ASSERT((block->status & BLOCK_IN_USE) &&
  2516. !(block->status &
  2517. (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH | BLOCK_REASSIGNED |
  2518. BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_FOR_UPDATE)));
  2519. /* Assert that the block is in a file_blocks chain. */
  2520. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  2521. /* Assert that the block is not in the LRU ring. */
  2522. DBUG_ASSERT(!block->next_used && !block->prev_used);
  2523. /*
  2524. IMHO the below condition (if()) makes no sense. I can't see how it
  2525. could be possible that free_block() is entered with a NULL hash_link
  2526. pointer. The only place where it can become NULL is in free_block()
  2527. (or before its first use ever, but for those blocks free_block() is
  2528. not called). I don't remove the conditional as it cannot harm, but
  2529. place an DBUG_ASSERT to confirm my hypothesis. Eventually the
  2530. condition (if()) can be removed.
  2531. */
  2532. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  2533. if (block->hash_link) {
  2534. /*
  2535. While waiting for readers to finish, new readers might request the
  2536. block. But since we set block->status|= BLOCK_REASSIGNED, they
  2537. will wait on block->wqueue[COND_FOR_SAVED]. They must be signalled
  2538. later.
  2539. */
  2540. block->status |= BLOCK_REASSIGNED;
  2541. wait_for_readers(keycache, block, thread_var);
  2542. /*
  2543. The block must not have been freed by another thread. Repeat some
  2544. checks. An additional requirement is that it must be read now
  2545. (BLOCK_READ).
  2546. */
  2547. DBUG_ASSERT(block->hash_link && block->hash_link->block == block);
  2548. DBUG_ASSERT(
  2549. (block->status & (BLOCK_READ | BLOCK_IN_USE | BLOCK_REASSIGNED)) &&
  2550. !(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
  2551. BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_FOR_UPDATE)));
  2552. DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
  2553. DBUG_ASSERT(!block->prev_used);
  2554. /*
  2555. Unset BLOCK_REASSIGNED again. If we hand the block to an evicting
  2556. thread (through unreg_request() below), other threads must not see
  2557. this flag. They could become confused.
  2558. */
  2559. block->status &= ~BLOCK_REASSIGNED;
  2560. /*
  2561. Do not release the hash_link until the block is off all lists.
  2562. At least not if we hand it over for eviction in unreg_request().
  2563. */
  2564. }
  2565. /*
  2566. Unregister the block request and link the block into the LRU ring.
  2567. This enables eviction for the block. If the LRU ring was empty and
  2568. threads are waiting for a block, then the block wil be handed over
  2569. for eviction immediately. Otherwise we will unlink it from the LRU
  2570. ring again, without releasing the lock in between. So decrementing
  2571. the request counter and updating statistics are the only relevant
  2572. operation in this case. Assert that there are no other requests
  2573. registered.
  2574. */
  2575. DBUG_ASSERT(block->requests == 1);
  2576. unreg_request(keycache, block, 0);
  2577. /*
  2578. Note that even without releasing the cache lock it is possible that
  2579. the block is immediately selected for eviction by link_block() and
  2580. thus not added to the LRU ring. In this case we must not touch the
  2581. block any more.
  2582. */
  2583. if (block->status & BLOCK_IN_EVICTION) return;
  2584. /* Error blocks are not put into the LRU ring. */
  2585. if (!(block->status & BLOCK_ERROR)) {
  2586. /* Here the block must be in the LRU ring. Unlink it again. */
  2587. DBUG_ASSERT(block->next_used && block->prev_used &&
  2588. *block->prev_used == block);
  2589. unlink_block(keycache, block);
  2590. }
  2591. if (block->temperature == BLOCK_WARM) keycache->warm_blocks--;
  2592. block->temperature = BLOCK_COLD;
  2593. /* Remove from file_blocks hash. */
  2594. unlink_changed(block);
  2595. /* Remove reference to block from hash table. */
  2596. unlink_hash(keycache, block->hash_link);
  2597. block->hash_link = NULL;
  2598. block->status = 0;
  2599. block->length = 0;
  2600. block->offset = keycache->key_cache_block_size;
  2601. /* Enforced by unlink_changed(), but just to be sure. */
  2602. DBUG_ASSERT(!block->next_changed && !block->prev_changed);
  2603. /* Enforced by unlink_block(): not in LRU ring nor in free_block_list. */
  2604. DBUG_ASSERT(!block->next_used && !block->prev_used);
  2605. /* Insert the free block in the free list. */
  2606. block->next_used = keycache->free_block_list;
  2607. keycache->free_block_list = block;
  2608. /* Keep track of the number of currently unused blocks. */
  2609. keycache->blocks_unused++;
  2610. /* All pending requests for this page must be resubmitted. */
  2611. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  2612. }
  2613. /*
  2614. Flush a portion of changed blocks to disk,
  2615. free used blocks if requested
  2616. */
  2617. static int flush_cached_blocks(KEY_CACHE *keycache,
  2618. st_keycache_thread_var *thread_var, File file,
  2619. BLOCK_LINK **cache, BLOCK_LINK **end,
  2620. enum flush_type type) {
  2621. int error;
  2622. int last_errno = 0;
  2623. uint count = (uint)(end - cache);
  2624. /* Don't lock the cache during the flush */
  2625. mysql_mutex_unlock(&keycache->cache_lock);
  2626. /*
  2627. As all blocks referred in 'cache' are marked by BLOCK_IN_FLUSH
  2628. we are guarunteed no thread will change them
  2629. */
  2630. std::sort(cache, cache + count, [](const BLOCK_LINK *a, const BLOCK_LINK *b) {
  2631. return a->hash_link->diskpos < b->hash_link->diskpos;
  2632. });
  2633. mysql_mutex_lock(&keycache->cache_lock);
  2634. /*
  2635. Note: Do not break the loop. We have registered a request on every
  2636. block in 'cache'. These must be unregistered by free_block() or
  2637. unreg_request().
  2638. */
  2639. for (; cache != end; cache++) {
  2640. BLOCK_LINK *block = *cache;
  2641. /*
  2642. If the block contents is going to be changed, we abandon the flush
  2643. for this block. flush_key_blocks_int() will restart its search and
  2644. handle the block properly.
  2645. */
  2646. if (!(block->status & BLOCK_FOR_UPDATE)) {
  2647. /* Blocks coming here must have a certain status. */
  2648. DBUG_ASSERT(block->hash_link);
  2649. DBUG_ASSERT(block->hash_link->block == block);
  2650. DBUG_ASSERT(block->hash_link->file == file);
  2651. DBUG_ASSERT((block->status & ~BLOCK_IN_EVICTION) ==
  2652. (BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
  2653. block->status |= BLOCK_IN_FLUSHWRITE;
  2654. mysql_mutex_unlock(&keycache->cache_lock);
  2655. error = (int)my_pwrite(file, block->buffer + block->offset,
  2656. block->length - block->offset,
  2657. block->hash_link->diskpos + block->offset,
  2658. MYF(MY_NABP | MY_WAIT_IF_FULL));
  2659. mysql_mutex_lock(&keycache->cache_lock);
  2660. keycache->global_cache_write++;
  2661. if (error) {
  2662. block->status |= BLOCK_ERROR;
  2663. if (!last_errno) last_errno = errno ? errno : -1;
  2664. }
  2665. block->status &= ~BLOCK_IN_FLUSHWRITE;
  2666. /* Block must not have changed status except BLOCK_FOR_UPDATE. */
  2667. DBUG_ASSERT(block->hash_link);
  2668. DBUG_ASSERT(block->hash_link->block == block);
  2669. DBUG_ASSERT(block->hash_link->file == file);
  2670. DBUG_ASSERT((block->status & ~(BLOCK_FOR_UPDATE | BLOCK_IN_EVICTION)) ==
  2671. (BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
  2672. /*
  2673. Set correct status and link in right queue for free or later use.
  2674. free_block() must not see BLOCK_CHANGED and it may need to wait
  2675. for readers of the block. These should not see the block in the
  2676. wrong hash. If not freeing the block, we need to have it in the
  2677. right queue anyway.
  2678. */
  2679. link_to_file_list(keycache, block, file, 1);
  2680. }
  2681. block->status &= ~BLOCK_IN_FLUSH;
  2682. /*
  2683. Let to proceed for possible waiting requests to write to the block page.
  2684. It might happen only during an operation to resize the key cache.
  2685. */
  2686. release_whole_queue(&block->wqueue[COND_FOR_SAVED]);
  2687. /* type will never be FLUSH_IGNORE_CHANGED here */
  2688. if (!(type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE) &&
  2689. !(block->status &
  2690. (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH | BLOCK_FOR_UPDATE))) {
  2691. /*
  2692. Note that a request has been registered against the block in
  2693. flush_key_blocks_int().
  2694. */
  2695. free_block(keycache, thread_var, block);
  2696. } else {
  2697. /*
  2698. Link the block into the LRU ring if it's the last submitted
  2699. request for the block. This enables eviction for the block.
  2700. Note that a request has been registered against the block in
  2701. flush_key_blocks_int().
  2702. */
  2703. unreg_request(keycache, block, 1);
  2704. }
  2705. } /* end of for ( ; cache != end ; cache++) */
  2706. return last_errno;
  2707. }
  2708. /*
  2709. Flush all key blocks for a file to disk, but don't do any mutex locks.
  2710. SYNOPSIS
  2711. flush_key_blocks_int()
  2712. keycache pointer to a key cache data structure
  2713. thread_var pointer to thread specific variables
  2714. file handler for the file to flush to
  2715. flush_type type of the flush
  2716. NOTES
  2717. This function doesn't do any mutex locks because it needs to be called both
  2718. from flush_key_blocks and flush_all_key_blocks (the later one does the
  2719. mutex lock in the resize_key_cache() function).
  2720. We do only care about changed blocks that exist when the function is
  2721. entered. We do not guarantee that all changed blocks of the file are
  2722. flushed if more blocks change while this function is running.
  2723. RETURN
  2724. 0 ok
  2725. 1 error
  2726. */
  2727. static int flush_key_blocks_int(KEY_CACHE *keycache,
  2728. st_keycache_thread_var *thread_var, File file,
  2729. enum flush_type type) {
  2730. BLOCK_LINK *cache_buff[FLUSH_CACHE], **cache;
  2731. int last_errno = 0;
  2732. int last_errcnt = 0;
  2733. DBUG_ENTER("flush_key_blocks_int");
  2734. DBUG_PRINT("enter", ("file: %d blocks_used: %lu blocks_changed: %lu", file,
  2735. keycache->blocks_used, keycache->blocks_changed));
  2736. cache = cache_buff;
  2737. if (keycache->disk_blocks > 0) {
  2738. /* Key cache exists and flush is not disabled */
  2739. int error = 0;
  2740. uint count = FLUSH_CACHE;
  2741. BLOCK_LINK **pos, **end;
  2742. BLOCK_LINK *first_in_switch = NULL;
  2743. BLOCK_LINK *last_in_flush;
  2744. BLOCK_LINK *last_for_update;
  2745. BLOCK_LINK *block, *next;
  2746. #ifndef DBUG_OFF
  2747. uint cnt = 0;
  2748. #endif
  2749. if (type != FLUSH_IGNORE_CHANGED) {
  2750. /*
  2751. Count how many key blocks we have to cache to be able
  2752. to flush all dirty pages with minimum seek moves
  2753. */
  2754. count = 0;
  2755. for (block = keycache->changed_blocks[FILE_HASH(file)]; block;
  2756. block = block->next_changed) {
  2757. if ((block->hash_link->file == file) &&
  2758. !(block->status & BLOCK_IN_FLUSH)) {
  2759. count++;
  2760. DBUG_ASSERT(count <= keycache->blocks_used);
  2761. }
  2762. }
  2763. /*
  2764. Allocate a new buffer only if its bigger than the one we have.
  2765. Assure that we always have some entries for the case that new
  2766. changed blocks appear while we need to wait for something.
  2767. */
  2768. if ((count > FLUSH_CACHE) &&
  2769. !(cache = (BLOCK_LINK **)my_malloc(
  2770. key_memory_KEY_CACHE, sizeof(BLOCK_LINK *) * count, MYF(0))))
  2771. cache = cache_buff;
  2772. /*
  2773. After a restart there could be more changed blocks than now.
  2774. So we should not let count become smaller than the fixed buffer.
  2775. */
  2776. if (cache == cache_buff) count = FLUSH_CACHE;
  2777. }
  2778. /* Retrieve the blocks and write them to a buffer to be flushed */
  2779. restart:
  2780. last_in_flush = NULL;
  2781. last_for_update = NULL;
  2782. end = (pos = cache) + count;
  2783. for (block = keycache->changed_blocks[FILE_HASH(file)]; block;
  2784. block = next) {
  2785. #ifndef DBUG_OFF
  2786. cnt++;
  2787. DBUG_ASSERT(cnt <= keycache->blocks_used);
  2788. #endif
  2789. next = block->next_changed;
  2790. if (block->hash_link->file == file) {
  2791. if (!(block->status & (BLOCK_IN_FLUSH | BLOCK_FOR_UPDATE))) {
  2792. /*
  2793. Note: The special handling of BLOCK_IN_SWITCH is obsolete
  2794. since we set BLOCK_IN_FLUSH if the eviction includes a
  2795. flush. It can be removed in a later version.
  2796. */
  2797. if (!(block->status & BLOCK_IN_SWITCH)) {
  2798. /*
  2799. We care only for the blocks for which flushing was not
  2800. initiated by another thread and which are not in eviction.
  2801. Registering a request on the block unlinks it from the LRU
  2802. ring and protects against eviction.
  2803. */
  2804. reg_requests(keycache, block, 1);
  2805. if (type != FLUSH_IGNORE_CHANGED) {
  2806. /* It's not a temporary file */
  2807. if (pos == end) {
  2808. /*
  2809. This should happen relatively seldom. Remove the
  2810. request because we won't do anything with the block
  2811. but restart and pick it again in the next iteration.
  2812. */
  2813. unreg_request(keycache, block, 0);
  2814. /*
  2815. This happens only if there is not enough
  2816. memory for the big block
  2817. */
  2818. if ((error = flush_cached_blocks(keycache, thread_var, file,
  2819. cache, end, type))) {
  2820. /* Do not loop infinitely trying to flush in vain. */
  2821. if ((last_errno == error) && (++last_errcnt > 5)) goto err;
  2822. last_errno = error;
  2823. }
  2824. /*
  2825. Restart the scan as some other thread might have changed
  2826. the changed blocks chain: the blocks that were in switch
  2827. state before the flush started have to be excluded
  2828. */
  2829. goto restart;
  2830. }
  2831. /*
  2832. Mark the block with BLOCK_IN_FLUSH in order not to let
  2833. other threads to use it for new pages and interfere with
  2834. our sequence of flushing dirty file pages. We must not
  2835. set this flag before actually putting the block on the
  2836. write burst array called 'cache'.
  2837. */
  2838. block->status |= BLOCK_IN_FLUSH;
  2839. /* Add block to the array for a write burst. */
  2840. *pos++ = block;
  2841. } else {
  2842. /* It's a temporary file */
  2843. DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
  2844. /*
  2845. free_block() must not be called with BLOCK_CHANGED. Note
  2846. that we must not change the BLOCK_CHANGED flag outside of
  2847. link_to_file_list() so that it is always in the correct
  2848. queue and the *blocks_changed counters are correct.
  2849. */
  2850. link_to_file_list(keycache, block, file, 1);
  2851. if (!(block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH))) {
  2852. /* A request has been registered against the block above. */
  2853. free_block(keycache, thread_var, block);
  2854. } else {
  2855. /*
  2856. Link the block into the LRU ring if it's the last
  2857. submitted request for the block. This enables eviction
  2858. for the block. A request has been registered against
  2859. the block above.
  2860. */
  2861. unreg_request(keycache, block, 1);
  2862. }
  2863. }
  2864. } else {
  2865. /*
  2866. Link the block into a list of blocks 'in switch'.
  2867. WARNING: Here we introduce a place where a changed block
  2868. is not in the changed_blocks hash! This is acceptable for
  2869. a BLOCK_IN_SWITCH. Never try this for another situation.
  2870. Other parts of the key cache code rely on changed blocks
  2871. being in the changed_blocks hash.
  2872. */
  2873. unlink_changed(block);
  2874. link_changed(block, &first_in_switch);
  2875. }
  2876. } else if (type != FLUSH_KEEP) {
  2877. /*
  2878. During the normal flush at end of statement (FLUSH_KEEP) we
  2879. do not need to ensure that blocks in flush or update by
  2880. other threads are flushed. They will be flushed by them
  2881. later. In all other cases we must assure that we do not have
  2882. any changed block of this file in the cache when this
  2883. function returns.
  2884. */
  2885. if (block->status & BLOCK_IN_FLUSH) {
  2886. /* Remember the last block found to be in flush. */
  2887. last_in_flush = block;
  2888. } else {
  2889. /* Remember the last block found to be selected for update. */
  2890. last_for_update = block;
  2891. }
  2892. }
  2893. }
  2894. }
  2895. if (pos != cache) {
  2896. if ((error = flush_cached_blocks(keycache, thread_var, file, cache, pos,
  2897. type))) {
  2898. /* Do not loop inifnitely trying to flush in vain. */
  2899. if ((last_errno == error) && (++last_errcnt > 5)) goto err;
  2900. last_errno = error;
  2901. }
  2902. /*
  2903. Do not restart here during the normal flush at end of statement
  2904. (FLUSH_KEEP). We have now flushed at least all blocks that were
  2905. changed when entering this function. In all other cases we must
  2906. assure that we do not have any changed block of this file in the
  2907. cache when this function returns.
  2908. */
  2909. if (type != FLUSH_KEEP) goto restart;
  2910. }
  2911. if (last_in_flush) {
  2912. /*
  2913. There are no blocks to be flushed by this thread, but blocks in
  2914. flush by other threads. Wait until one of the blocks is flushed.
  2915. Re-check the condition for last_in_flush. We may have unlocked
  2916. the cache_lock in flush_cached_blocks(). The state of the block
  2917. could have changed.
  2918. */
  2919. if (last_in_flush->status & BLOCK_IN_FLUSH)
  2920. wait_on_queue(&last_in_flush->wqueue[COND_FOR_SAVED],
  2921. &keycache->cache_lock, thread_var);
  2922. /* Be sure not to lose a block. They may be flushed in random order. */
  2923. goto restart;
  2924. }
  2925. if (last_for_update) {
  2926. /*
  2927. There are no blocks to be flushed by this thread, but blocks for
  2928. update by other threads. Wait until one of the blocks is updated.
  2929. Re-check the condition for last_for_update. We may have unlocked
  2930. the cache_lock in flush_cached_blocks(). The state of the block
  2931. could have changed.
  2932. */
  2933. if (last_for_update->status & BLOCK_FOR_UPDATE)
  2934. wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
  2935. &keycache->cache_lock, thread_var);
  2936. /* The block is now changed. Flush it. */
  2937. goto restart;
  2938. }
  2939. /*
  2940. Wait until the list of blocks in switch is empty. The threads that
  2941. are switching these blocks will relink them to clean file chains
  2942. while we wait and thus empty the 'first_in_switch' chain.
  2943. */
  2944. while (first_in_switch) {
  2945. #ifndef DBUG_OFF
  2946. cnt = 0;
  2947. #endif
  2948. wait_on_queue(&first_in_switch->wqueue[COND_FOR_SAVED],
  2949. &keycache->cache_lock, thread_var);
  2950. #ifndef DBUG_OFF
  2951. cnt++;
  2952. DBUG_ASSERT(cnt <= keycache->blocks_used);
  2953. #endif
  2954. /*
  2955. Do not restart here. We have flushed all blocks that were
  2956. changed when entering this function and were not marked for
  2957. eviction. Other threads have now flushed all remaining blocks in
  2958. the course of their eviction.
  2959. */
  2960. }
  2961. if (!(type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE)) {
  2962. BLOCK_LINK *last_for_update = NULL;
  2963. BLOCK_LINK *last_in_switch = NULL;
  2964. uint total_found = 0;
  2965. uint found;
  2966. /*
  2967. Finally free all clean blocks for this file.
  2968. During resize this may be run by two threads in parallel.
  2969. */
  2970. do {
  2971. found = 0;
  2972. for (block = keycache->file_blocks[FILE_HASH(file)]; block;
  2973. block = next) {
  2974. /* Remember the next block. After freeing we cannot get at it. */
  2975. next = block->next_changed;
  2976. /* Changed blocks cannot appear in the file_blocks hash. */
  2977. DBUG_ASSERT(!(block->status & BLOCK_CHANGED));
  2978. if (block->hash_link->file == file) {
  2979. /* We must skip blocks that will be changed. */
  2980. if (block->status & BLOCK_FOR_UPDATE) {
  2981. last_for_update = block;
  2982. continue;
  2983. }
  2984. /*
  2985. We must not free blocks in eviction (BLOCK_IN_EVICTION |
  2986. BLOCK_IN_SWITCH) or blocks intended to be freed
  2987. (BLOCK_REASSIGNED).
  2988. */
  2989. if (!(block->status &
  2990. (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH | BLOCK_REASSIGNED))) {
  2991. HASH_LINK *next_hash_link = NULL;
  2992. my_off_t next_diskpos = 0;
  2993. File next_file = 0;
  2994. uint next_status = 0;
  2995. uint hash_requests = 0;
  2996. total_found++;
  2997. found++;
  2998. DBUG_ASSERT(found <= keycache->blocks_used);
  2999. /*
  3000. Register a request. This unlinks the block from the LRU
  3001. ring and protects it against eviction. This is required
  3002. by free_block().
  3003. */
  3004. reg_requests(keycache, block, 1);
  3005. /*
  3006. free_block() may need to wait for readers of the block.
  3007. This is the moment where the other thread can move the
  3008. 'next' block from the chain. free_block() needs to wait
  3009. if there are requests for the block pending.
  3010. */
  3011. if (next && (hash_requests = block->hash_link->requests)) {
  3012. /* Copy values from the 'next' block and its hash_link. */
  3013. next_status = next->status;
  3014. next_hash_link = next->hash_link;
  3015. next_diskpos = next_hash_link->diskpos;
  3016. next_file = next_hash_link->file;
  3017. DBUG_ASSERT(next == next_hash_link->block);
  3018. }
  3019. free_block(keycache, thread_var, block);
  3020. /*
  3021. If we had to wait and the state of the 'next' block
  3022. changed, break the inner loop. 'next' may no longer be
  3023. part of the current chain.
  3024. We do not want to break the loop after every free_block(),
  3025. not even only after waits. The chain might be quite long
  3026. and contain blocks for many files. Traversing it again and
  3027. again to find more blocks for this file could become quite
  3028. inefficient.
  3029. */
  3030. if (next && hash_requests &&
  3031. ((next_status != next->status) ||
  3032. (next_hash_link != next->hash_link) ||
  3033. (next_file != next_hash_link->file) ||
  3034. (next_diskpos != next_hash_link->diskpos) ||
  3035. (next != next_hash_link->block)))
  3036. break;
  3037. } else {
  3038. last_in_switch = block;
  3039. }
  3040. }
  3041. } /* end for block in file_blocks */
  3042. } while (found);
  3043. /*
  3044. If any clean block has been found, we may have waited for it to
  3045. become free. In this case it could be possible that another clean
  3046. block became dirty. This is possible if the write request existed
  3047. before the flush started (BLOCK_FOR_UPDATE). Re-check the hashes.
  3048. */
  3049. if (total_found) goto restart;
  3050. /*
  3051. To avoid an infinite loop, wait until one of the blocks marked
  3052. for update is updated.
  3053. */
  3054. if (last_for_update) {
  3055. /* We did not wait. Block must not have changed status. */
  3056. DBUG_ASSERT(last_for_update->status & BLOCK_FOR_UPDATE);
  3057. wait_on_queue(&last_for_update->wqueue[COND_FOR_REQUESTED],
  3058. &keycache->cache_lock, thread_var);
  3059. goto restart;
  3060. }
  3061. /*
  3062. To avoid an infinite loop wait until one of the blocks marked
  3063. for eviction is switched.
  3064. */
  3065. if (last_in_switch) {
  3066. /* We did not wait. Block must not have changed status. */
  3067. DBUG_ASSERT(last_in_switch->status &
  3068. (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH | BLOCK_REASSIGNED));
  3069. wait_on_queue(&last_in_switch->wqueue[COND_FOR_SAVED],
  3070. &keycache->cache_lock, thread_var);
  3071. goto restart;
  3072. }
  3073. } /* if (! (type == FLUSH_KEEP || type == FLUSH_FORCE_WRITE)) */
  3074. } /* if (keycache->disk_blocks > 0 */
  3075. err:
  3076. if (cache != cache_buff) my_free(cache);
  3077. if (last_errno) errno = last_errno; /* Return first error */
  3078. DBUG_RETURN(last_errno != 0);
  3079. }
  3080. /*
  3081. Flush all blocks for a file to disk
  3082. SYNOPSIS
  3083. flush_key_blocks()
  3084. keycache pointer to a key cache data structure
  3085. thread_var pointer to thread specific variables
  3086. file handler for the file to flush to
  3087. flush_type type of the flush
  3088. RETURN
  3089. 0 ok
  3090. 1 error
  3091. */
  3092. int flush_key_blocks(KEY_CACHE *keycache, st_keycache_thread_var *thread_var,
  3093. File file, enum flush_type type) {
  3094. int res = 0;
  3095. DBUG_ENTER("flush_key_blocks");
  3096. DBUG_PRINT("enter", ("keycache: %p", keycache));
  3097. if (!keycache->key_cache_inited) DBUG_RETURN(0);
  3098. mysql_mutex_lock(&keycache->cache_lock);
  3099. /* While waiting for lock, keycache could have been ended. */
  3100. if (keycache->disk_blocks > 0) {
  3101. inc_counter_for_resize_op(keycache);
  3102. res = flush_key_blocks_int(keycache, thread_var, file, type);
  3103. dec_counter_for_resize_op(keycache);
  3104. }
  3105. mysql_mutex_unlock(&keycache->cache_lock);
  3106. DBUG_RETURN(res);
  3107. }
  3108. /*
  3109. Flush all blocks in the key cache to disk.
  3110. SYNOPSIS
  3111. flush_all_key_blocks()
  3112. keycache pointer to key cache root structure
  3113. thread_var pointer to thread specific variables
  3114. DESCRIPTION
  3115. Flushing of the whole key cache is done in two phases.
  3116. 1. Flush all changed blocks, waiting for them if necessary. Loop
  3117. until there is no changed block left in the cache.
  3118. 2. Free all clean blocks. Normally this means free all blocks. The
  3119. changed blocks were flushed in phase 1 and became clean. However we
  3120. may need to wait for blocks that are read by other threads. While we
  3121. wait, a clean block could become changed if that operation started
  3122. before the resize operation started. To be safe we must restart at
  3123. phase 1.
  3124. When we can run through the changed_blocks and file_blocks hashes
  3125. without finding a block any more, then we are done.
  3126. Note that we hold keycache->cache_lock all the time unless we need
  3127. to wait for something.
  3128. RETURN
  3129. 0 OK
  3130. != 0 Error
  3131. */
  3132. static int flush_all_key_blocks(KEY_CACHE *keycache,
  3133. st_keycache_thread_var *thread_var) {
  3134. BLOCK_LINK *block;
  3135. uint total_found;
  3136. uint found;
  3137. uint idx;
  3138. DBUG_ENTER("flush_all_key_blocks");
  3139. do {
  3140. mysql_mutex_assert_owner(&keycache->cache_lock);
  3141. total_found = 0;
  3142. /*
  3143. Phase1: Flush all changed blocks, waiting for them if necessary.
  3144. Loop until there is no changed block left in the cache.
  3145. */
  3146. do {
  3147. found = 0;
  3148. /* Step over the whole changed_blocks hash array. */
  3149. for (idx = 0; idx < CHANGED_BLOCKS_HASH; idx++) {
  3150. /*
  3151. If an array element is non-empty, use the first block from its
  3152. chain to find a file for flush. All changed blocks for this
  3153. file are flushed. So the same block will not appear at this
  3154. place again with the next iteration. New writes for blocks are
  3155. not accepted during the flush. If multiple files share the
  3156. same hash bucket, one of them will be flushed per iteration
  3157. of the outer loop of phase 1.
  3158. */
  3159. if ((block = keycache->changed_blocks[idx])) {
  3160. found++;
  3161. /*
  3162. Flush dirty blocks but do not free them yet. They can be used
  3163. for reading until all other blocks are flushed too.
  3164. */
  3165. if (flush_key_blocks_int(keycache, thread_var, block->hash_link->file,
  3166. FLUSH_FORCE_WRITE))
  3167. DBUG_RETURN(1);
  3168. }
  3169. }
  3170. } while (found);
  3171. /*
  3172. Phase 2: Free all clean blocks. Normally this means free all
  3173. blocks. The changed blocks were flushed in phase 1 and became
  3174. clean. However we may need to wait for blocks that are read by
  3175. other threads. While we wait, a clean block could become changed
  3176. if that operation started before the resize operation started. To
  3177. be safe we must restart at phase 1.
  3178. */
  3179. do {
  3180. found = 0;
  3181. /* Step over the whole file_blocks hash array. */
  3182. for (idx = 0; idx < CHANGED_BLOCKS_HASH; idx++) {
  3183. /*
  3184. If an array element is non-empty, use the first block from its
  3185. chain to find a file for flush. All blocks for this file are
  3186. freed. So the same block will not appear at this place again
  3187. with the next iteration. If multiple files share the
  3188. same hash bucket, one of them will be flushed per iteration
  3189. of the outer loop of phase 2.
  3190. */
  3191. if ((block = keycache->file_blocks[idx])) {
  3192. total_found++;
  3193. found++;
  3194. if (flush_key_blocks_int(keycache, thread_var, block->hash_link->file,
  3195. FLUSH_RELEASE))
  3196. DBUG_RETURN(1);
  3197. }
  3198. }
  3199. } while (found);
  3200. /*
  3201. If any clean block has been found, we may have waited for it to
  3202. become free. In this case it could be possible that another clean
  3203. block became dirty. This is possible if the write request existed
  3204. before the resize started (BLOCK_FOR_UPDATE). Re-check the hashes.
  3205. */
  3206. } while (total_found);
  3207. #ifndef DBUG_OFF
  3208. /* Now there should not exist any block any more. */
  3209. for (idx = 0; idx < CHANGED_BLOCKS_HASH; idx++) {
  3210. DBUG_ASSERT(!keycache->changed_blocks[idx]);
  3211. DBUG_ASSERT(!keycache->file_blocks[idx]);
  3212. }
  3213. #endif
  3214. DBUG_RETURN(0);
  3215. }
  3216. /*
  3217. Reset the counters of a key cache.
  3218. SYNOPSIS
  3219. reset_key_cache_counters()
  3220. name the name of a key cache
  3221. key_cache pointer to the key kache to be reset
  3222. DESCRIPTION
  3223. This procedure is used by process_key_caches() to reset the counters of all
  3224. currently used key caches, both the default one and the named ones.
  3225. RETURN
  3226. 0 on success (always because it can't fail)
  3227. */
  3228. int reset_key_cache_counters(const char *name MY_ATTRIBUTE((unused)),
  3229. KEY_CACHE *key_cache) {
  3230. DBUG_ENTER("reset_key_cache_counters");
  3231. if (!key_cache->key_cache_inited) {
  3232. DBUG_PRINT("info", ("Key cache %s not initialized.", name));
  3233. DBUG_RETURN(0);
  3234. }
  3235. DBUG_PRINT("info", ("Resetting counters for key cache %s.", name));
  3236. key_cache->global_blocks_changed = 0; /* Key_blocks_not_flushed */
  3237. key_cache->global_cache_r_requests = 0; /* Key_read_requests */
  3238. key_cache->global_cache_read = 0; /* Key_reads */
  3239. key_cache->global_cache_w_requests = 0; /* Key_write_requests */
  3240. key_cache->global_cache_write = 0; /* Key_writes */
  3241. DBUG_RETURN(0);
  3242. }
  3243. #if !defined(DBUG_OFF)
  3244. #define F_B_PRT(_f_, _v_) DBUG_PRINT("assert_fail", (_f_, _v_))
  3245. static int fail_block(BLOCK_LINK *block) {
  3246. F_B_PRT("block->next_used: %p\n", block->next_used);
  3247. F_B_PRT("block->prev_used: %p\n", block->prev_used);
  3248. F_B_PRT("block->next_changed: %p\n", block->next_changed);
  3249. F_B_PRT("block->prev_changed: %p\n", block->prev_changed);
  3250. F_B_PRT("block->hash_link: %p\n", block->hash_link);
  3251. F_B_PRT("block->status: %u\n", block->status);
  3252. F_B_PRT("block->length: %u\n", block->length);
  3253. F_B_PRT("block->offset: %u\n", block->offset);
  3254. F_B_PRT("block->requests: %u\n", block->requests);
  3255. F_B_PRT("block->temperature: %u\n", block->temperature);
  3256. return 0; /* Let the assert fail. */
  3257. }
  3258. static int fail_hlink(HASH_LINK *hlink) {
  3259. F_B_PRT("hlink->next: %p\n", hlink->next);
  3260. F_B_PRT("hlink->prev: %p\n", hlink->prev);
  3261. F_B_PRT("hlink->block: %p\n", hlink->block);
  3262. F_B_PRT("hlink->diskpos: %lu\n", (ulong)hlink->diskpos);
  3263. F_B_PRT("hlink->file: %d\n", hlink->file);
  3264. return 0; /* Let the assert fail. */
  3265. }
  3266. static int cache_empty(KEY_CACHE *keycache) {
  3267. char buf[512];
  3268. int errcnt = 0;
  3269. int idx;
  3270. if (keycache->disk_blocks <= 0) return 1;
  3271. for (idx = 0; idx < keycache->disk_blocks; idx++) {
  3272. BLOCK_LINK *block = keycache->block_root + idx;
  3273. if (block->status || block->requests || block->hash_link) {
  3274. snprintf(buf, sizeof(buf) - 1, "block index: %u", idx);
  3275. my_message_local(INFORMATION_LEVEL, EE_DEBUG_INFO, buf);
  3276. fail_block(block);
  3277. errcnt++;
  3278. }
  3279. }
  3280. for (idx = 0; idx < keycache->hash_links; idx++) {
  3281. HASH_LINK *hash_link = keycache->hash_link_root + idx;
  3282. if (hash_link->requests || hash_link->block) {
  3283. snprintf(buf, sizeof(buf) - 1, "hash_link index: %u", idx);
  3284. my_message_local(INFORMATION_LEVEL, EE_DEBUG_INFO, buf);
  3285. fail_hlink(hash_link);
  3286. errcnt++;
  3287. }
  3288. }
  3289. if (errcnt) {
  3290. snprintf(buf, sizeof(buf) - 1, "blocks: %d used: %lu",
  3291. keycache->disk_blocks, keycache->blocks_used);
  3292. my_message_local(INFORMATION_LEVEL, EE_DEBUG_INFO, buf);
  3293. snprintf(buf, sizeof(buf) - 1, "hash_links: %d used: %d",
  3294. keycache->hash_links, keycache->hash_links_used);
  3295. my_message_local(INFORMATION_LEVEL, EE_DEBUG_INFO, buf);
  3296. }
  3297. return !errcnt;
  3298. }
  3299. #endif