|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
线上或者测试环境经常出现的误操作总是让DBA同学那么闹心。application
PURPOSE
=======
ThepurposeofthisarticleistoprovideanunderstandingofFREELISTSandFREELISTGROUPS.SCOPE&APPLICATION
===================
ThisarticleisintendedtobeusedbyDBAstohelpunderstandhowFREELISTSandFREELISTGROUPwork.FREELISTSandFREELISTGROUPS=============================
Thefollowingbulletiniscomprisedofseveralparts:1.IntroductiontoOracledatablockorganization2.FreeListOverview3.FreeListTypes4.ConsiderationsforOptimizingSpaceManagement5.Algorithms6.FreeListsinOracle
1.Introduction:
=============BeforegoingintothedetailsoffreelistmanagementonemustknowhowtheOracledatablocksareorganized.EveryobjectinanOracledatabasewhichoccupiesspaceisassociatedwithasegment.Asegmentisasetofextentsthatcontainsallthedataforaspecificlogicalstoragestructurewithinatablespace.Thereare4segmenttypes:opermanentdatasegment(table,cluster)oindexsegmentorollbacksegmentotemporarydatasegmentEachsegmentismadeupofsmallerstorageunitscalledextents.Anextentisastorageunitcomposedofcontiguousblocks.Eachsegmentisinitiallycreatedinthedatabasewithatleastoneextent(controlledbyparameterMINEXTENTS).Thoughempty,thespaceisreserved.Whentheinitialspaceisfull,anewextentisdynamicallyallocated.ThenewextentsizeisdeterminedbytheparametersNEXTandPCTINCREASE.ThedynamicallocationsstopwhenthenumberofextentsreachesthevalueofparameterMAXEXTENTS.ThefirstblockofthefirstextentofeachsegmentisreservedbyOracletostoresysteminformationanditiscalledthesegmentheader.TheSegmentHeadercontains:oTheExtentsTableoTheFreeListsdescriptorsoTheHighWaterMark(HWM)TheHWMmarksalimitinthesegmentwhereeachblockbelowis"inuse",andeachblockabovehasneverbeenused.TheHWMalwaysincreasesinsize;Itisresetto"zero"(positiontothestartofthesegment)whenaTRUNCATEisissued.
2.FreeListOverview
==================StartingwithV7.3,itisnowpossibletocreateasegmenteitherwithalimitednumberofextentsorwithanunlimitednumberofextents.Toaccommodatethis,fivenewblocktypesareintroduced:14:UnlimitedRollbackSegmentHeader15:UnlimitedDeferredRollbackSegmentHeader16:UnlimitedDataSegmentHeader17:UnlimitedDataSegmentHeaderwithFLgroups18:ExtentMapBlockForeachdatasegment,OraclekeepstrackofblockshavingavailablefreespaceforincomingINSERTorUPDATE.FreeSpacecomesfrom2ways:1.AllblocksbeyondtheHWMthatareallocatedbutnotused.2.AllblocksbelowtheHWMlinkedinafreelist,andcandidatestobereused.AFreeListisconstitutedof:oFlagtoindicateifthefreelistisused(1)orunused(0)oDBAoftheblockheadoftheFreeListChain,oDBAoftheblocktailoftheFreeListChain.IneachDataBlockthereisaflagtoindicateiftheblockislinkedinaFreeListchain.IftheflagissettheblockwillalsopointtotheDBAofthenextblockinthefreelistchain.Azerovaluemeansthatthecurrentblockisthelastblockinthechain.
3.FreeListTypes:
================
TheMasterFreeListorCommonFreespacepool:===============================================Thereisonlyoneforeachsegment.Itisimplicitlyallocatedatsegmentcreationtime.Foreachdatasegmentthereisapool,commonforeachprocess,ofblockscontainingfreespaceavailableforincominginsertscalledtheMasterfreelist.Everyprocesshasaccesstothiscommonpool.So,thelevelofcontentionincreaseswhenseveralprocesssimultaneouslywanttoinsertrowsinthesamesegment.TheblocksofinitialextentsallocatedatsegmentcreationtimeandofthenewonesdynamicallyallocatedarelinkedtotheMasterfreelist.
TheProcessFreeLists:=======================ToreducecontentionproblemsontheMasterFreelist,anotherleveloffreelistsisavailablewhichiscalledtheProcessfreelists,ExplicitlycreatedwhentheFREELISTSparameterhasbeenspecifiedinaCREATE/ALTERcommand.PartitioningtheFreeSpaceinmultiplefreelistsisusedessentiallytoimprovetheperformanceofOLTPapplicationswithahighdegreeofconcurrenttransactionsperforminginsertsorupdatesrequiringnewspaceallocation.ParameterFREELISTShasbeenaddedintheSTORAGEclauseofaCREATETABLE/CLUSTERorINDEX.Example:CREATETABLEflg(....)...STORAGE(...FREELISTS10...);Thenumberofprocessfreelistsmustbeclosetothemaximumnumberofconcurrentprocessperformingsimultaneouslyinsertsinthesegment.Itisimportanttonotethatthisimprovestheinsertsperformance,butwastesdiskspaceusage.EachprocessismappedtoaProcessfreelistbyitsOraclePID(ProcessID):Processfreelistentry=(P%NFL)+1whereP:OraclePIDoftheprocess(indexinV$PROCESS),andNFL:ProcessfreelistsnumberasdefinedbyparameterFREELISTSThe
TransactionFreeLists:===========================ImplicitlyallocatedbyOracleasneeded.ATransactionFreeListisafreelistdedicatedtoonetransactionandonlyone.Thereareaminimumof16transactionsfreelistspersegment,andthisnumberincreasesaslongasitisnecessary,untilitreachesthelimitoftheSegmentHeaderblocksize.AtransactionneedstoallocateaTxFreeListsentrywhen:oItreleasesspaceinablock(DELETEorUPDATE)oAndifithasnotalreadyallocatedone.
4.ConsiderationsforOptimizingSpaceManagement:===============================================ThetwoparametersPCTFREEandPCTUSEDoftheStorageClauseinaCREATE/ALTERstatement,areusedtocontrolandoptimizespacemanagementwithinadatasegmentblock(table,cluster).PCTFREEspecifiesthepercentageofadatablocktobereserved(keptfree)forpossibleupdatestorowsthatalreadyarecontainedinthatblock.Afterablockbecomesfull,asdeterminedbyPCTFREE,OracledoesnotconsidertheblockisfortheinsertionofnewrowsuntilthepercentageoftheblockbeingusedfallsbelowtheparameterPCTUSED.Itisadvisedthatthespacecalculatedas(100%-(PCTFREE+PCTUSED))begreaterthanthemaximumsizeofatablerow.5.Algorithms:===========AblockisputonfreelistifthefreespaceintheblockisgreaterthanthespacereservedbyPCTFREE.Blockslinkedinafreelistareavailableforfutureupdatesorinserts.Ablockisunlinkedfromafreelistifthefreespaceintheblockisnotenoughtoallowanewrowinsert,andifthepercentageoftheusedspaceremainsabovePCTUSED.AblockisrelinkedtoafreelistifafterDELETEorUPDATEoperations,thepercentageoftheusedspacefallsbelowPCTUSED.Eachtimeablockisaddedtoafreelist,itislinkedattheheadofthechain.Example:~~~~~~~~Attimet0,2blocksareonfreelist:datablocks1and3:FL:B1->B3Attimet1,deletionsaredoneonblockB2suchastheblockhastoberelinkedtoFreelist:FL:B2->B1->B3AdatablockisputonFreelistonlyifitisnotalreadylinked.TransactionFreeListAlgorithms:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~TheTxfreelistallocationprocessstartsbyscanningallTxfreelistsallocatedinthesegmentHeaderblockandcheckingifaTxfreelistentryhasnotalreadybeenallocatedtothetransaction.Else,itlooksforanunusedentryoranemptyTxfreelistbelongingtoa"committed"transaction.Ifthesearchfails,anewentryintheTxfreelistsareaisallocated.WhenthereisnochancetoexpandtheTxFreelistsarea,theunfortunatetransactionhastowaitforanentryrelease.Theselectedentryisdeterminedby(PID%Txfreeliststotalnumber).PIDistheOracleprocessId.ThewaitisdonebyrequestinginSmodetheTXenqueueheldbythetransactionTowningtheTxfreelistentry.ThewaitwillendwhenTcommits.ThespacefreedinablockbyatransactionT1(DELETEorUPDATE):oisimmediatelyreusablebyT1,owillbereusableforothertransactionsonlyafterT1commitsandwhenlookingforspaceinthisblock.Example:~~~~~~~~5.1TransactionT1deletessomerowsintableT.Theseoperationsreleasesomespaceinblock10inthesegment.ThepercentageoftheremainingusedspacefallsbelowPCTUSED:blockcanbereusedforincominginserts,itisputonfreelist.Todothis,TransactionT1needstoallocateanentryintheTransactionfreelistsareaintheSegmentHeaderblock,thenlinkstheblock10inthecorrespondingfreelist.5.2.TransactionT2wantstoinsertanewrowintableT.ThespacefreedbyT1,inblock10,cannotbereused.AssumethatT2doesnothaveaTxfreelistallocatedinthesegment(becauseT2hasnotreleasedspaceinthesegment)5.2.1T2startswalkingonitsProcessFreeList(PrFL)lookingforafreeblock.(Letsassumethatthereare3blocksonthePrFLandtheydonthaveenoughfreespaceT2needs.)5.2.2Thefirstblockfailsthecheck.Theblockmustbeexchanged(movetothenextblockonthelist)withanotherone.ThisblockhastobeunlinkedfromthefreelistiftheusedspaceintheblockgoesbeyondthespacedefinedbyPCTUSEDor,ifthe"UNLINKcounter"isbelowaparticularthreshold.(Thedefaultvalueis5).Theideabehindthisisnottokeepblocksthatfailduringfreespacesearchattheheadoffreelists.TheUNLINKactionisdoneonlyifthecurrentblockisheadofthefreelistchain.5.2.3AfteralltheblocksonthePrFLarecheckedandnoblockisfound,theblockselectionintheprocessfreelistisstopped5.2.4OracletriestomoveblocksfromMasterfreelisttoProcessfreelist.ThisoperationiscalledFreeListsMerge.Thenumberofblockstomoveisdefinedbyaconstantanditis5.Searchwillcontinuefromstep5.2.1NotethatatthispointOracleWILLNOTlookattheotherPrFLeventhoughtheremightbeemptyblocksonthoselists.Thiswillcausesomespacetobewastedtemporarily.5.2.5(AssumethattherearenomoreblocksontheMasterFreeList)OracletriesnowtogetblocksfromtheotherTxfreelists(committed).TheTxfreelistsentriesintheheaderblockarescanned,lookingfornotemptyand"committed"entries.Forthoseentries,ALLtheblocksaremovedtotheMasterFreelist.Then,onlyapart(5)oftheblocksinMasterfreelistaremovedagaintoprocessfreelist.IfthereareblocksmovedfromtheTxFltotheMsFL,gotostep2.15.2.6(If2.5fails)OracletriestobumpuptheHWM.Toreducecontentiononsegmentheaderblock,OraclebumpsuptheHWMbymblocksatatime.Thenumbermis:1:iftheblockdoesnothavetogoonfreelist,1:ifweareontheinitialextent(0)andtheHWMis<=4(smalltable)min(5,unusedblocksintheextent):before7.2min(5*(NFL+1),unusedblocksintheextent):since7.2.Intheexample,weassumeHWMisattheendoftheextent.5.2.7Newextentallocation.ThenewblocksaremovedtoMasterfreelist.Freeblocksearchcontinuesfromstep2.45.3TransactionT1wantsnowtoinsertanewrowintableT.First,itlooksforavailablespaceinblockslinkedtoitstransactionfreelist.Theblock10hasavailablespace,andthefreespaceinitisenoughtothespacerequiredbythenewrow,block10isselected.ThepercentageoftheusedspaceintheblockgoesupabovePCTUSED,theblockhastobeunlinkedfromthetransactionfreelist.6.FreelistsGroups:=================Inmulti-instances(OracleParallelServer),toreducecontentiononthesegmentheaderblock,whichcontainsthefreelistsdescriptorsofthesegment,itispossibletoallocateotherspecialblockstostorefreelistsdescriptors.ThesegroupsarecalledtheFreeListsGroups.FREELISTGROUPSisintroducedinSTORAGEclauseofaCREATETABLE/CLUSTERorINDEX.Example:~~~~~~~~CREATETABLEflg(....)...STORAGE(...FREELISTGROUPS2FREELISTS10...);EachfreelistgroupisassociatedwithaspecialblockcalledtheFreeListBlock.Theseblockswillbeallocatedrightafterthesegmentheader.So,ifandobjectiscreatedwith2freelistgroups,thefirstblockofthefirstextentwillbethesegmentheaderblockandthesecondandthirdblockswillbethefreelistblocks.TheseblocksstoreaMasterfreelist(ofthegroup),andasmuchprocessfreelistsasspecifiedbyparameterFREELISTS.TherestoftheblockdedicatedtoTransactionsfreelists.InthesegmentheaderblockofanobjectwithfreelistgroupsthereisonlyonefreelistcalledTheSuperMasterFreelistortheSegmentMasterfreelist.Thefreelistgroupsreducecontentiononthesegmentheaderblock,andreduceinter-instance"pinging",atthecostofexcessivediskspaceconsumption.ThealgorithmtomapaFreelistGroup,definedonasegmentS,toaprocessPofaninstanceI,isthefollowing:where:NFB:numberofFreelistGroupsdefinedonsegmentS,P:OraclePIDoftheprocess(fromV$PROCESS),I:INSTANCE_NUMBERparameter(ifsetinINIT.ORA)orparameterTHREADvalueMAXINST:maximumofinstancessharingthesamedatabase(MAXINSTANCESparameterofCREATEDATABASE).InanonOPSenvironmentorOPSandSingle-Instanceenvironment:Freelistgroupis:(P%NFB)+1Inamulti-instanceenvironment(OPS):oIfNFB<=MAXINST:Freelistgroupis:((I-1)%NFB)+1oIfNFB>MAXINST:RANGE=NFB/MAXINST;INITIAL=(RANGE*(I-1))+1REST=NFB-(RANGE*MAXINST)if(I-1)<RESTFreelistgroupis:INITIAL+(P%(RANGE+1))if(I-1)>=RESTFreelistgroupis:INITIAL+REST+(P%RANGE)TRUNCATINGATABLE:~~~~~~~~~~~~~~~~~~~Forthegiventableandallindexassociatedtoit,theTRUNCATEoperationdoesthefollowingtasks:1.Getexclusiveaccesstothesegmentheader.IfthesegmentheaderislockedprocesshastowaititsreleasebyrequestingaTXlockinSharedmode.2.Lockthesegmentheader.3.Flushallblocksbelongingtothissegmentinthebuffercachetodisk.4.Clearallthefreelistsinthesegmentheaderblockandinallfreelistgroupsblocks(iffreelistgroupsaredefined).ThebeforeimageofallthechangesarerecordedintheRollbacksegment.5.Truncatethesegment:theHWMreturnstoitsinitialposition(extent0andblock0iftableor1ifindex).Thebeforeimageofthechangeisrecordedintherollbacksegment.6.TrimalltheextentsbeyondMINEXTENTS.7.IfOPS,flushondiskthesegmentheaderblockandfreelistgroupsblocks.NOTE:Performancevs.Space===========================Ascanbeseenfromthealgorithmsabove,usingmultiplefreelistsmaycausesomeemptyblockstogounused,causingthesegmenttoextend.Ifperformanceiscritical,multiplefreelistscanbeusedtoimproveconcurrentaccess,possiblyattheexpenseofadditionalspaceused.However,ifspaceistheprimaryconsideration,thenasinglefreelistshouldbeused,leavingFREELISTS=1,withouttheperformancebenefitsforconcurrenttransactions
优化的SQL查询算法,有效地提高查询速度 |
|