sched.c 153 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155
  1. /*
  2. * kernel/sched.c
  3. *
  4. * Kernel scheduler and related syscalls
  5. *
  6. * Copyright (C) 1991-2002 Linus Torvalds
  7. *
  8. * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
  9. * make semaphores SMP safe
  10. * 1998-11-19 Implemented schedule_timeout() and related stuff
  11. * by Andrea Arcangeli
  12. * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
  13. * hybrid priority-list and round-robin design with
  14. * an array-switch method of distributing timeslices
  15. * and per-CPU runqueues. Cleanups and useful suggestions
  16. * by Davide Libenzi, preemptible kernel bits by Robert Love.
  17. * 2003-09-03 Interactivity tuning by Con Kolivas.
  18. * 2004-04-02 Scheduler domains code by Nick Piggin
  19. */
  20. #include <linux/mm.h>
  21. #include <linux/module.h>
  22. #include <linux/nmi.h>
  23. #include <linux/init.h>
  24. #include <asm/uaccess.h>
  25. #include <linux/highmem.h>
  26. #include <linux/smp_lock.h>
  27. #include <asm/mmu_context.h>
  28. #include <linux/interrupt.h>
  29. #include <linux/capability.h>
  30. #include <linux/completion.h>
  31. #include <linux/kernel_stat.h>
  32. #include <linux/security.h>
  33. #include <linux/notifier.h>
  34. #include <linux/profile.h>
  35. #include <linux/suspend.h>
  36. #include <linux/vmalloc.h>
  37. #include <linux/blkdev.h>
  38. #include <linux/delay.h>
  39. #include <linux/smp.h>
  40. #include <linux/threads.h>
  41. #include <linux/timer.h>
  42. #include <linux/rcupdate.h>
  43. #include <linux/cpu.h>
  44. #include <linux/cpuset.h>
  45. #include <linux/percpu.h>
  46. #include <linux/kthread.h>
  47. #include <linux/seq_file.h>
  48. #include <linux/syscalls.h>
  49. #include <linux/times.h>
  50. #include <linux/acct.h>
  51. #include <asm/tlb.h>
  52. #include <asm/unistd.h>
  53. /*
  54. * Convert user-nice values [ -20 ... 0 ... 19 ]
  55. * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
  56. * and back.
  57. */
  58. #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
  59. #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
  60. #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
  61. /*
  62. * 'User priority' is the nice value converted to something we
  63. * can work with better when scaling various scheduler parameters,
  64. * it's a [ 0 ... 39 ] range.
  65. */
  66. #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
  67. #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
  68. #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
  69. /*
  70. * Some helpers for converting nanosecond timing to jiffy resolution
  71. */
  72. #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
  73. #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
  74. /*
  75. * These are the 'tuning knobs' of the scheduler:
  76. *
  77. * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
  78. * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
  79. * Timeslices get refilled after they expire.
  80. */
  81. #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
  82. #define DEF_TIMESLICE (100 * HZ / 1000)
  83. #define ON_RUNQUEUE_WEIGHT 30
  84. #define CHILD_PENALTY 95
  85. #define PARENT_PENALTY 100
  86. #define EXIT_WEIGHT 3
  87. #define PRIO_BONUS_RATIO 25
  88. #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
  89. #define INTERACTIVE_DELTA 2
  90. #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
  91. #define STARVATION_LIMIT (MAX_SLEEP_AVG)
  92. #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
  93. /*
  94. * If a task is 'interactive' then we reinsert it in the active
  95. * array after it has expired its current timeslice. (it will not
  96. * continue to run immediately, it will still roundrobin with
  97. * other interactive tasks.)
  98. *
  99. * This part scales the interactivity limit depending on niceness.
  100. *
  101. * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
  102. * Here are a few examples of different nice levels:
  103. *
  104. * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
  105. * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
  106. * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
  107. * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
  108. * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
  109. *
  110. * (the X axis represents the possible -5 ... 0 ... +5 dynamic
  111. * priority range a task can explore, a value of '1' means the
  112. * task is rated interactive.)
  113. *
  114. * Ie. nice +19 tasks can never get 'interactive' enough to be
  115. * reinserted into the active array. And only heavily CPU-hog nice -20
  116. * tasks will be expired. Default nice 0 tasks are somewhere between,
  117. * it takes some effort for them to get interactive, but it's not
  118. * too hard.
  119. */
  120. #define CURRENT_BONUS(p) \
  121. (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
  122. MAX_SLEEP_AVG)
  123. #define GRANULARITY (10 * HZ / 1000 ? : 1)
  124. #ifdef CONFIG_SMP
  125. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  126. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
  127. num_online_cpus())
  128. #else
  129. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  130. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
  131. #endif
  132. #define SCALE(v1,v1_max,v2_max) \
  133. (v1) * (v2_max) / (v1_max)
  134. #define DELTA(p) \
  135. (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
  136. #define TASK_INTERACTIVE(p) \
  137. ((p)->prio <= (p)->static_prio - DELTA(p))
  138. #define INTERACTIVE_SLEEP(p) \
  139. (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
  140. (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
  141. #define TASK_PREEMPTS_CURR(p, rq) \
  142. ((p)->prio < (rq)->curr->prio)
  143. /*
  144. * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
  145. * to time slice values: [800ms ... 100ms ... 5ms]
  146. *
  147. * The higher a thread's priority, the bigger timeslices
  148. * it gets during one round of execution. But even the lowest
  149. * priority thread gets MIN_TIMESLICE worth of execution time.
  150. */
  151. #define SCALE_PRIO(x, prio) \
  152. max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
  153. static unsigned int task_timeslice(task_t *p)
  154. {
  155. if (p->static_prio < NICE_TO_PRIO(0))
  156. return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
  157. else
  158. return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
  159. }
  160. #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
  161. < (long long) (sd)->cache_hot_time)
  162. void __put_task_struct_cb(struct rcu_head *rhp)
  163. {
  164. __put_task_struct(container_of(rhp, struct task_struct, rcu));
  165. }
  166. EXPORT_SYMBOL_GPL(__put_task_struct_cb);
  167. /*
  168. * These are the runqueue data structures:
  169. */
  170. #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
  171. typedef struct runqueue runqueue_t;
  172. struct prio_array {
  173. unsigned int nr_active;
  174. unsigned long bitmap[BITMAP_SIZE];
  175. struct list_head queue[MAX_PRIO];
  176. };
  177. /*
  178. * This is the main, per-CPU runqueue data structure.
  179. *
  180. * Locking rule: those places that want to lock multiple runqueues
  181. * (such as the load balancing or the thread migration code), lock
  182. * acquire operations must be ordered by ascending &runqueue.
  183. */
  184. struct runqueue {
  185. spinlock_t lock;
  186. /*
  187. * nr_running and cpu_load should be in the same cacheline because
  188. * remote CPUs use both these fields when doing load calculation.
  189. */
  190. unsigned long nr_running;
  191. #ifdef CONFIG_SMP
  192. unsigned long cpu_load[3];
  193. #endif
  194. unsigned long long nr_switches;
  195. /*
  196. * This is part of a global counter where only the total sum
  197. * over all CPUs matters. A task can increase this counter on
  198. * one CPU and if it got migrated afterwards it may decrease
  199. * it on another CPU. Always updated under the runqueue lock:
  200. */
  201. unsigned long nr_uninterruptible;
  202. unsigned long expired_timestamp;
  203. unsigned long long timestamp_last_tick;
  204. task_t *curr, *idle;
  205. struct mm_struct *prev_mm;
  206. prio_array_t *active, *expired, arrays[2];
  207. int best_expired_prio;
  208. atomic_t nr_iowait;
  209. #ifdef CONFIG_SMP
  210. struct sched_domain *sd;
  211. /* For active balancing */
  212. int active_balance;
  213. int push_cpu;
  214. task_t *migration_thread;
  215. struct list_head migration_queue;
  216. #endif
  217. #ifdef CONFIG_SCHEDSTATS
  218. /* latency stats */
  219. struct sched_info rq_sched_info;
  220. /* sys_sched_yield() stats */
  221. unsigned long yld_exp_empty;
  222. unsigned long yld_act_empty;
  223. unsigned long yld_both_empty;
  224. unsigned long yld_cnt;
  225. /* schedule() stats */
  226. unsigned long sched_switch;
  227. unsigned long sched_cnt;
  228. unsigned long sched_goidle;
  229. /* try_to_wake_up() stats */
  230. unsigned long ttwu_cnt;
  231. unsigned long ttwu_local;
  232. #endif
  233. };
  234. static DEFINE_PER_CPU(struct runqueue, runqueues);
  235. /*
  236. * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
  237. * See detach_destroy_domains: synchronize_sched for details.
  238. *
  239. * The domain tree of any CPU may only be accessed from within
  240. * preempt-disabled sections.
  241. */
  242. #define for_each_domain(cpu, domain) \
  243. for (domain = rcu_dereference(cpu_rq(cpu)->sd); domain; domain = domain->parent)
  244. #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
  245. #define this_rq() (&__get_cpu_var(runqueues))
  246. #define task_rq(p) cpu_rq(task_cpu(p))
  247. #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
  248. #ifndef prepare_arch_switch
  249. # define prepare_arch_switch(next) do { } while (0)
  250. #endif
  251. #ifndef finish_arch_switch
  252. # define finish_arch_switch(prev) do { } while (0)
  253. #endif
  254. #ifndef __ARCH_WANT_UNLOCKED_CTXSW
  255. static inline int task_running(runqueue_t *rq, task_t *p)
  256. {
  257. return rq->curr == p;
  258. }
  259. static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
  260. {
  261. }
  262. static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
  263. {
  264. #ifdef CONFIG_DEBUG_SPINLOCK
  265. /* this is a valid case when another task releases the spinlock */
  266. rq->lock.owner = current;
  267. #endif
  268. spin_unlock_irq(&rq->lock);
  269. }
  270. #else /* __ARCH_WANT_UNLOCKED_CTXSW */
  271. static inline int task_running(runqueue_t *rq, task_t *p)
  272. {
  273. #ifdef CONFIG_SMP
  274. return p->oncpu;
  275. #else
  276. return rq->curr == p;
  277. #endif
  278. }
  279. static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
  280. {
  281. #ifdef CONFIG_SMP
  282. /*
  283. * We can optimise this out completely for !SMP, because the
  284. * SMP rebalancing from interrupt is the only thing that cares
  285. * here.
  286. */
  287. next->oncpu = 1;
  288. #endif
  289. #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  290. spin_unlock_irq(&rq->lock);
  291. #else
  292. spin_unlock(&rq->lock);
  293. #endif
  294. }
  295. static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
  296. {
  297. #ifdef CONFIG_SMP
  298. /*
  299. * After ->oncpu is cleared, the task can be moved to a different CPU.
  300. * We must ensure this doesn't happen until the switch is completely
  301. * finished.
  302. */
  303. smp_wmb();
  304. prev->oncpu = 0;
  305. #endif
  306. #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  307. local_irq_enable();
  308. #endif
  309. }
  310. #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
  311. /*
  312. * task_rq_lock - lock the runqueue a given task resides on and disable
  313. * interrupts. Note the ordering: we can safely lookup the task_rq without
  314. * explicitly disabling preemption.
  315. */
  316. static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
  317. __acquires(rq->lock)
  318. {
  319. struct runqueue *rq;
  320. repeat_lock_task:
  321. local_irq_save(*flags);
  322. rq = task_rq(p);
  323. spin_lock(&rq->lock);
  324. if (unlikely(rq != task_rq(p))) {
  325. spin_unlock_irqrestore(&rq->lock, *flags);
  326. goto repeat_lock_task;
  327. }
  328. return rq;
  329. }
  330. static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
  331. __releases(rq->lock)
  332. {
  333. spin_unlock_irqrestore(&rq->lock, *flags);
  334. }
  335. #ifdef CONFIG_SCHEDSTATS
  336. /*
  337. * bump this up when changing the output format or the meaning of an existing
  338. * format, so that tools can adapt (or abort)
  339. */
  340. #define SCHEDSTAT_VERSION 12
  341. static int show_schedstat(struct seq_file *seq, void *v)
  342. {
  343. int cpu;
  344. seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
  345. seq_printf(seq, "timestamp %lu\n", jiffies);
  346. for_each_online_cpu(cpu) {
  347. runqueue_t *rq = cpu_rq(cpu);
  348. #ifdef CONFIG_SMP
  349. struct sched_domain *sd;
  350. int dcnt = 0;
  351. #endif
  352. /* runqueue-specific stats */
  353. seq_printf(seq,
  354. "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
  355. cpu, rq->yld_both_empty,
  356. rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
  357. rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
  358. rq->ttwu_cnt, rq->ttwu_local,
  359. rq->rq_sched_info.cpu_time,
  360. rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
  361. seq_printf(seq, "\n");
  362. #ifdef CONFIG_SMP
  363. /* domain-specific stats */
  364. preempt_disable();
  365. for_each_domain(cpu, sd) {
  366. enum idle_type itype;
  367. char mask_str[NR_CPUS];
  368. cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
  369. seq_printf(seq, "domain%d %s", dcnt++, mask_str);
  370. for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
  371. itype++) {
  372. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
  373. sd->lb_cnt[itype],
  374. sd->lb_balanced[itype],
  375. sd->lb_failed[itype],
  376. sd->lb_imbalance[itype],
  377. sd->lb_gained[itype],
  378. sd->lb_hot_gained[itype],
  379. sd->lb_nobusyq[itype],
  380. sd->lb_nobusyg[itype]);
  381. }
  382. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
  383. sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
  384. sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
  385. sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
  386. sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
  387. }
  388. preempt_enable();
  389. #endif
  390. }
  391. return 0;
  392. }
  393. static int schedstat_open(struct inode *inode, struct file *file)
  394. {
  395. unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
  396. char *buf = kmalloc(size, GFP_KERNEL);
  397. struct seq_file *m;
  398. int res;
  399. if (!buf)
  400. return -ENOMEM;
  401. res = single_open(file, show_schedstat, NULL);
  402. if (!res) {
  403. m = file->private_data;
  404. m->buf = buf;
  405. m->size = size;
  406. } else
  407. kfree(buf);
  408. return res;
  409. }
  410. struct file_operations proc_schedstat_operations = {
  411. .open = schedstat_open,
  412. .read = seq_read,
  413. .llseek = seq_lseek,
  414. .release = single_release,
  415. };
  416. # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
  417. # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
  418. #else /* !CONFIG_SCHEDSTATS */
  419. # define schedstat_inc(rq, field) do { } while (0)
  420. # define schedstat_add(rq, field, amt) do { } while (0)
  421. #endif
  422. /*
  423. * rq_lock - lock a given runqueue and disable interrupts.
  424. */
  425. static inline runqueue_t *this_rq_lock(void)
  426. __acquires(rq->lock)
  427. {
  428. runqueue_t *rq;
  429. local_irq_disable();
  430. rq = this_rq();
  431. spin_lock(&rq->lock);
  432. return rq;
  433. }
  434. #ifdef CONFIG_SCHEDSTATS
  435. /*
  436. * Called when a process is dequeued from the active array and given
  437. * the cpu. We should note that with the exception of interactive
  438. * tasks, the expired queue will become the active queue after the active
  439. * queue is empty, without explicitly dequeuing and requeuing tasks in the
  440. * expired queue. (Interactive tasks may be requeued directly to the
  441. * active queue, thus delaying tasks in the expired queue from running;
  442. * see scheduler_tick()).
  443. *
  444. * This function is only called from sched_info_arrive(), rather than
  445. * dequeue_task(). Even though a task may be queued and dequeued multiple
  446. * times as it is shuffled about, we're really interested in knowing how
  447. * long it was from the *first* time it was queued to the time that it
  448. * finally hit a cpu.
  449. */
  450. static inline void sched_info_dequeued(task_t *t)
  451. {
  452. t->sched_info.last_queued = 0;
  453. }
  454. /*
  455. * Called when a task finally hits the cpu. We can now calculate how
  456. * long it was waiting to run. We also note when it began so that we
  457. * can keep stats on how long its timeslice is.
  458. */
  459. static void sched_info_arrive(task_t *t)
  460. {
  461. unsigned long now = jiffies, diff = 0;
  462. struct runqueue *rq = task_rq(t);
  463. if (t->sched_info.last_queued)
  464. diff = now - t->sched_info.last_queued;
  465. sched_info_dequeued(t);
  466. t->sched_info.run_delay += diff;
  467. t->sched_info.last_arrival = now;
  468. t->sched_info.pcnt++;
  469. if (!rq)
  470. return;
  471. rq->rq_sched_info.run_delay += diff;
  472. rq->rq_sched_info.pcnt++;
  473. }
  474. /*
  475. * Called when a process is queued into either the active or expired
  476. * array. The time is noted and later used to determine how long we
  477. * had to wait for us to reach the cpu. Since the expired queue will
  478. * become the active queue after active queue is empty, without dequeuing
  479. * and requeuing any tasks, we are interested in queuing to either. It
  480. * is unusual but not impossible for tasks to be dequeued and immediately
  481. * requeued in the same or another array: this can happen in sched_yield(),
  482. * set_user_nice(), and even load_balance() as it moves tasks from runqueue
  483. * to runqueue.
  484. *
  485. * This function is only called from enqueue_task(), but also only updates
  486. * the timestamp if it is already not set. It's assumed that
  487. * sched_info_dequeued() will clear that stamp when appropriate.
  488. */
  489. static inline void sched_info_queued(task_t *t)
  490. {
  491. if (!t->sched_info.last_queued)
  492. t->sched_info.last_queued = jiffies;
  493. }
  494. /*
  495. * Called when a process ceases being the active-running process, either
  496. * voluntarily or involuntarily. Now we can calculate how long we ran.
  497. */
  498. static inline void sched_info_depart(task_t *t)
  499. {
  500. struct runqueue *rq = task_rq(t);
  501. unsigned long diff = jiffies - t->sched_info.last_arrival;
  502. t->sched_info.cpu_time += diff;
  503. if (rq)
  504. rq->rq_sched_info.cpu_time += diff;
  505. }
  506. /*
  507. * Called when tasks are switched involuntarily due, typically, to expiring
  508. * their time slice. (This may also be called when switching to or from
  509. * the idle task.) We are only called when prev != next.
  510. */
  511. static inline void sched_info_switch(task_t *prev, task_t *next)
  512. {
  513. struct runqueue *rq = task_rq(prev);
  514. /*
  515. * prev now departs the cpu. It's not interesting to record
  516. * stats about how efficient we were at scheduling the idle
  517. * process, however.
  518. */
  519. if (prev != rq->idle)
  520. sched_info_depart(prev);
  521. if (next != rq->idle)
  522. sched_info_arrive(next);
  523. }
  524. #else
  525. #define sched_info_queued(t) do { } while (0)
  526. #define sched_info_switch(t, next) do { } while (0)
  527. #endif /* CONFIG_SCHEDSTATS */
  528. /*
  529. * Adding/removing a task to/from a priority array:
  530. */
  531. static void dequeue_task(struct task_struct *p, prio_array_t *array)
  532. {
  533. array->nr_active--;
  534. list_del(&p->run_list);
  535. if (list_empty(array->queue + p->prio))
  536. __clear_bit(p->prio, array->bitmap);
  537. }
  538. static void enqueue_task(struct task_struct *p, prio_array_t *array)
  539. {
  540. sched_info_queued(p);
  541. list_add_tail(&p->run_list, array->queue + p->prio);
  542. __set_bit(p->prio, array->bitmap);
  543. array->nr_active++;
  544. p->array = array;
  545. }
  546. /*
  547. * Put task to the end of the run list without the overhead of dequeue
  548. * followed by enqueue.
  549. */
  550. static void requeue_task(struct task_struct *p, prio_array_t *array)
  551. {
  552. list_move_tail(&p->run_list, array->queue + p->prio);
  553. }
  554. static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
  555. {
  556. list_add(&p->run_list, array->queue + p->prio);
  557. __set_bit(p->prio, array->bitmap);
  558. array->nr_active++;
  559. p->array = array;
  560. }
  561. /*
  562. * effective_prio - return the priority that is based on the static
  563. * priority but is modified by bonuses/penalties.
  564. *
  565. * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
  566. * into the -5 ... 0 ... +5 bonus/penalty range.
  567. *
  568. * We use 25% of the full 0...39 priority range so that:
  569. *
  570. * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
  571. * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
  572. *
  573. * Both properties are important to certain workloads.
  574. */
  575. static int effective_prio(task_t *p)
  576. {
  577. int bonus, prio;
  578. if (rt_task(p))
  579. return p->prio;
  580. bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
  581. prio = p->static_prio - bonus;
  582. if (prio < MAX_RT_PRIO)
  583. prio = MAX_RT_PRIO;
  584. if (prio > MAX_PRIO-1)
  585. prio = MAX_PRIO-1;
  586. return prio;
  587. }
  588. /*
  589. * __activate_task - move a task to the runqueue.
  590. */
  591. static inline void __activate_task(task_t *p, runqueue_t *rq)
  592. {
  593. enqueue_task(p, rq->active);
  594. rq->nr_running++;
  595. }
  596. /*
  597. * __activate_idle_task - move idle task to the _front_ of runqueue.
  598. */
  599. static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
  600. {
  601. enqueue_task_head(p, rq->active);
  602. rq->nr_running++;
  603. }
  604. static int recalc_task_prio(task_t *p, unsigned long long now)
  605. {
  606. /* Caller must always ensure 'now >= p->timestamp' */
  607. unsigned long long __sleep_time = now - p->timestamp;
  608. unsigned long sleep_time;
  609. if (unlikely(p->policy == SCHED_BATCH))
  610. sleep_time = 0;
  611. else {
  612. if (__sleep_time > NS_MAX_SLEEP_AVG)
  613. sleep_time = NS_MAX_SLEEP_AVG;
  614. else
  615. sleep_time = (unsigned long)__sleep_time;
  616. }
  617. if (likely(sleep_time > 0)) {
  618. /*
  619. * User tasks that sleep a long time are categorised as
  620. * idle and will get just interactive status to stay active &
  621. * prevent them suddenly becoming cpu hogs and starving
  622. * other processes.
  623. */
  624. if (p->mm && p->activated != -1 &&
  625. sleep_time > INTERACTIVE_SLEEP(p)) {
  626. p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
  627. DEF_TIMESLICE);
  628. } else {
  629. /*
  630. * The lower the sleep avg a task has the more
  631. * rapidly it will rise with sleep time.
  632. */
  633. sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
  634. /*
  635. * Tasks waking from uninterruptible sleep are
  636. * limited in their sleep_avg rise as they
  637. * are likely to be waiting on I/O
  638. */
  639. if (p->activated == -1 && p->mm) {
  640. if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
  641. sleep_time = 0;
  642. else if (p->sleep_avg + sleep_time >=
  643. INTERACTIVE_SLEEP(p)) {
  644. p->sleep_avg = INTERACTIVE_SLEEP(p);
  645. sleep_time = 0;
  646. }
  647. }
  648. /*
  649. * This code gives a bonus to interactive tasks.
  650. *
  651. * The boost works by updating the 'average sleep time'
  652. * value here, based on ->timestamp. The more time a
  653. * task spends sleeping, the higher the average gets -
  654. * and the higher the priority boost gets as well.
  655. */
  656. p->sleep_avg += sleep_time;
  657. if (p->sleep_avg > NS_MAX_SLEEP_AVG)
  658. p->sleep_avg = NS_MAX_SLEEP_AVG;
  659. }
  660. }
  661. return effective_prio(p);
  662. }
  663. /*
  664. * activate_task - move a task to the runqueue and do priority recalculation
  665. *
  666. * Update all the scheduling statistics stuff. (sleep average
  667. * calculation, priority modifiers, etc.)
  668. */
  669. static void activate_task(task_t *p, runqueue_t *rq, int local)
  670. {
  671. unsigned long long now;
  672. now = sched_clock();
  673. #ifdef CONFIG_SMP
  674. if (!local) {
  675. /* Compensate for drifting sched_clock */
  676. runqueue_t *this_rq = this_rq();
  677. now = (now - this_rq->timestamp_last_tick)
  678. + rq->timestamp_last_tick;
  679. }
  680. #endif
  681. if (!rt_task(p))
  682. p->prio = recalc_task_prio(p, now);
  683. /*
  684. * This checks to make sure it's not an uninterruptible task
  685. * that is now waking up.
  686. */
  687. if (!p->activated) {
  688. /*
  689. * Tasks which were woken up by interrupts (ie. hw events)
  690. * are most likely of interactive nature. So we give them
  691. * the credit of extending their sleep time to the period
  692. * of time they spend on the runqueue, waiting for execution
  693. * on a CPU, first time around:
  694. */
  695. if (in_interrupt())
  696. p->activated = 2;
  697. else {
  698. /*
  699. * Normal first-time wakeups get a credit too for
  700. * on-runqueue time, but it will be weighted down:
  701. */
  702. p->activated = 1;
  703. }
  704. }
  705. p->timestamp = now;
  706. __activate_task(p, rq);
  707. }
  708. /*
  709. * deactivate_task - remove a task from the runqueue.
  710. */
  711. static void deactivate_task(struct task_struct *p, runqueue_t *rq)
  712. {
  713. rq->nr_running--;
  714. dequeue_task(p, p->array);
  715. p->array = NULL;
  716. }
  717. /*
  718. * resched_task - mark a task 'to be rescheduled now'.
  719. *
  720. * On UP this means the setting of the need_resched flag, on SMP it
  721. * might also involve a cross-CPU call to trigger the scheduler on
  722. * the target CPU.
  723. */
  724. #ifdef CONFIG_SMP
  725. static void resched_task(task_t *p)
  726. {
  727. int cpu;
  728. assert_spin_locked(&task_rq(p)->lock);
  729. if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
  730. return;
  731. set_tsk_thread_flag(p, TIF_NEED_RESCHED);
  732. cpu = task_cpu(p);
  733. if (cpu == smp_processor_id())
  734. return;
  735. /* NEED_RESCHED must be visible before we test POLLING_NRFLAG */
  736. smp_mb();
  737. if (!test_tsk_thread_flag(p, TIF_POLLING_NRFLAG))
  738. smp_send_reschedule(cpu);
  739. }
  740. #else
  741. static inline void resched_task(task_t *p)
  742. {
  743. assert_spin_locked(&task_rq(p)->lock);
  744. set_tsk_need_resched(p);
  745. }
  746. #endif
  747. /**
  748. * task_curr - is this task currently executing on a CPU?
  749. * @p: the task in question.
  750. */
  751. inline int task_curr(const task_t *p)
  752. {
  753. return cpu_curr(task_cpu(p)) == p;
  754. }
  755. #ifdef CONFIG_SMP
  756. typedef struct {
  757. struct list_head list;
  758. task_t *task;
  759. int dest_cpu;
  760. struct completion done;
  761. } migration_req_t;
  762. /*
  763. * The task's runqueue lock must be held.
  764. * Returns true if you have to wait for migration thread.
  765. */
  766. static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
  767. {
  768. runqueue_t *rq = task_rq(p);
  769. /*
  770. * If the task is not on a runqueue (and not running), then
  771. * it is sufficient to simply update the task's cpu field.
  772. */
  773. if (!p->array && !task_running(rq, p)) {
  774. set_task_cpu(p, dest_cpu);
  775. return 0;
  776. }
  777. init_completion(&req->done);
  778. req->task = p;
  779. req->dest_cpu = dest_cpu;
  780. list_add(&req->list, &rq->migration_queue);
  781. return 1;
  782. }
  783. /*
  784. * wait_task_inactive - wait for a thread to unschedule.
  785. *
  786. * The caller must ensure that the task *will* unschedule sometime soon,
  787. * else this function might spin for a *long* time. This function can't
  788. * be called with interrupts off, or it may introduce deadlock with
  789. * smp_call_function() if an IPI is sent by the same process we are
  790. * waiting to become inactive.
  791. */
  792. void wait_task_inactive(task_t *p)
  793. {
  794. unsigned long flags;
  795. runqueue_t *rq;
  796. int preempted;
  797. repeat:
  798. rq = task_rq_lock(p, &flags);
  799. /* Must be off runqueue entirely, not preempted. */
  800. if (unlikely(p->array || task_running(rq, p))) {
  801. /* If it's preempted, we yield. It could be a while. */
  802. preempted = !task_running(rq, p);
  803. task_rq_unlock(rq, &flags);
  804. cpu_relax();
  805. if (preempted)
  806. yield();
  807. goto repeat;
  808. }
  809. task_rq_unlock(rq, &flags);
  810. }
  811. /***
  812. * kick_process - kick a running thread to enter/exit the kernel
  813. * @p: the to-be-kicked thread
  814. *
  815. * Cause a process which is running on another CPU to enter
  816. * kernel-mode, without any delay. (to get signals handled.)
  817. *
  818. * NOTE: this function doesnt have to take the runqueue lock,
  819. * because all it wants to ensure is that the remote task enters
  820. * the kernel. If the IPI races and the task has been migrated
  821. * to another CPU then no harm is done and the purpose has been
  822. * achieved as well.
  823. */
  824. void kick_process(task_t *p)
  825. {
  826. int cpu;
  827. preempt_disable();
  828. cpu = task_cpu(p);
  829. if ((cpu != smp_processor_id()) && task_curr(p))
  830. smp_send_reschedule(cpu);
  831. preempt_enable();
  832. }
  833. /*
  834. * Return a low guess at the load of a migration-source cpu.
  835. *
  836. * We want to under-estimate the load of migration sources, to
  837. * balance conservatively.
  838. */
  839. static inline unsigned long source_load(int cpu, int type)
  840. {
  841. runqueue_t *rq = cpu_rq(cpu);
  842. unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
  843. if (type == 0)
  844. return load_now;
  845. return min(rq->cpu_load[type-1], load_now);
  846. }
  847. /*
  848. * Return a high guess at the load of a migration-target cpu
  849. */
  850. static inline unsigned long target_load(int cpu, int type)
  851. {
  852. runqueue_t *rq = cpu_rq(cpu);
  853. unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
  854. if (type == 0)
  855. return load_now;
  856. return max(rq->cpu_load[type-1], load_now);
  857. }
  858. /*
  859. * find_idlest_group finds and returns the least busy CPU group within the
  860. * domain.
  861. */
  862. static struct sched_group *
  863. find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
  864. {
  865. struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
  866. unsigned long min_load = ULONG_MAX, this_load = 0;
  867. int load_idx = sd->forkexec_idx;
  868. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  869. do {
  870. unsigned long load, avg_load;
  871. int local_group;
  872. int i;
  873. /* Skip over this group if it has no CPUs allowed */
  874. if (!cpus_intersects(group->cpumask, p->cpus_allowed))
  875. goto nextgroup;
  876. local_group = cpu_isset(this_cpu, group->cpumask);
  877. /* Tally up the load of all CPUs in the group */
  878. avg_load = 0;
  879. for_each_cpu_mask(i, group->cpumask) {
  880. /* Bias balancing toward cpus of our domain */
  881. if (local_group)
  882. load = source_load(i, load_idx);
  883. else
  884. load = target_load(i, load_idx);
  885. avg_load += load;
  886. }
  887. /* Adjust by relative CPU power of the group */
  888. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  889. if (local_group) {
  890. this_load = avg_load;
  891. this = group;
  892. } else if (avg_load < min_load) {
  893. min_load = avg_load;
  894. idlest = group;
  895. }
  896. nextgroup:
  897. group = group->next;
  898. } while (group != sd->groups);
  899. if (!idlest || 100*this_load < imbalance*min_load)
  900. return NULL;
  901. return idlest;
  902. }
  903. /*
  904. * find_idlest_queue - find the idlest runqueue among the cpus in group.
  905. */
  906. static int
  907. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  908. {
  909. cpumask_t tmp;
  910. unsigned long load, min_load = ULONG_MAX;
  911. int idlest = -1;
  912. int i;
  913. /* Traverse only the allowed CPUs */
  914. cpus_and(tmp, group->cpumask, p->cpus_allowed);
  915. for_each_cpu_mask(i, tmp) {
  916. load = source_load(i, 0);
  917. if (load < min_load || (load == min_load && i == this_cpu)) {
  918. min_load = load;
  919. idlest = i;
  920. }
  921. }
  922. return idlest;
  923. }
  924. /*
  925. * sched_balance_self: balance the current task (running on cpu) in domains
  926. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  927. * SD_BALANCE_EXEC.
  928. *
  929. * Balance, ie. select the least loaded group.
  930. *
  931. * Returns the target CPU number, or the same CPU if no balancing is needed.
  932. *
  933. * preempt must be disabled.
  934. */
  935. static int sched_balance_self(int cpu, int flag)
  936. {
  937. struct task_struct *t = current;
  938. struct sched_domain *tmp, *sd = NULL;
  939. for_each_domain(cpu, tmp)
  940. if (tmp->flags & flag)
  941. sd = tmp;
  942. while (sd) {
  943. cpumask_t span;
  944. struct sched_group *group;
  945. int new_cpu;
  946. int weight;
  947. span = sd->span;
  948. group = find_idlest_group(sd, t, cpu);
  949. if (!group)
  950. goto nextlevel;
  951. new_cpu = find_idlest_cpu(group, t, cpu);
  952. if (new_cpu == -1 || new_cpu == cpu)
  953. goto nextlevel;
  954. /* Now try balancing at a lower domain level */
  955. cpu = new_cpu;
  956. nextlevel:
  957. sd = NULL;
  958. weight = cpus_weight(span);
  959. for_each_domain(cpu, tmp) {
  960. if (weight <= cpus_weight(tmp->span))
  961. break;
  962. if (tmp->flags & flag)
  963. sd = tmp;
  964. }
  965. /* while loop will break here if sd == NULL */
  966. }
  967. return cpu;
  968. }
  969. #endif /* CONFIG_SMP */
  970. /*
  971. * wake_idle() will wake a task on an idle cpu if task->cpu is
  972. * not idle and an idle cpu is available. The span of cpus to
  973. * search starts with cpus closest then further out as needed,
  974. * so we always favor a closer, idle cpu.
  975. *
  976. * Returns the CPU we should wake onto.
  977. */
  978. #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
  979. static int wake_idle(int cpu, task_t *p)
  980. {
  981. cpumask_t tmp;
  982. struct sched_domain *sd;
  983. int i;
  984. if (idle_cpu(cpu))
  985. return cpu;
  986. for_each_domain(cpu, sd) {
  987. if (sd->flags & SD_WAKE_IDLE) {
  988. cpus_and(tmp, sd->span, p->cpus_allowed);
  989. for_each_cpu_mask(i, tmp) {
  990. if (idle_cpu(i))
  991. return i;
  992. }
  993. }
  994. else
  995. break;
  996. }
  997. return cpu;
  998. }
  999. #else
  1000. static inline int wake_idle(int cpu, task_t *p)
  1001. {
  1002. return cpu;
  1003. }
  1004. #endif
  1005. /***
  1006. * try_to_wake_up - wake up a thread
  1007. * @p: the to-be-woken-up thread
  1008. * @state: the mask of task states that can be woken
  1009. * @sync: do a synchronous wakeup?
  1010. *
  1011. * Put it on the run-queue if it's not already there. The "current"
  1012. * thread is always on the run-queue (except when the actual
  1013. * re-schedule is in progress), and as such you're allowed to do
  1014. * the simpler "current->state = TASK_RUNNING" to mark yourself
  1015. * runnable without the overhead of this.
  1016. *
  1017. * returns failure only if the task is already active.
  1018. */
  1019. static int try_to_wake_up(task_t *p, unsigned int state, int sync)
  1020. {
  1021. int cpu, this_cpu, success = 0;
  1022. unsigned long flags;
  1023. long old_state;
  1024. runqueue_t *rq;
  1025. #ifdef CONFIG_SMP
  1026. unsigned long load, this_load;
  1027. struct sched_domain *sd, *this_sd = NULL;
  1028. int new_cpu;
  1029. #endif
  1030. rq = task_rq_lock(p, &flags);
  1031. old_state = p->state;
  1032. if (!(old_state & state))
  1033. goto out;
  1034. if (p->array)
  1035. goto out_running;
  1036. cpu = task_cpu(p);
  1037. this_cpu = smp_processor_id();
  1038. #ifdef CONFIG_SMP
  1039. if (unlikely(task_running(rq, p)))
  1040. goto out_activate;
  1041. new_cpu = cpu;
  1042. schedstat_inc(rq, ttwu_cnt);
  1043. if (cpu == this_cpu) {
  1044. schedstat_inc(rq, ttwu_local);
  1045. goto out_set_cpu;
  1046. }
  1047. for_each_domain(this_cpu, sd) {
  1048. if (cpu_isset(cpu, sd->span)) {
  1049. schedstat_inc(sd, ttwu_wake_remote);
  1050. this_sd = sd;
  1051. break;
  1052. }
  1053. }
  1054. if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
  1055. goto out_set_cpu;
  1056. /*
  1057. * Check for affine wakeup and passive balancing possibilities.
  1058. */
  1059. if (this_sd) {
  1060. int idx = this_sd->wake_idx;
  1061. unsigned int imbalance;
  1062. imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
  1063. load = source_load(cpu, idx);
  1064. this_load = target_load(this_cpu, idx);
  1065. new_cpu = this_cpu; /* Wake to this CPU if we can */
  1066. if (this_sd->flags & SD_WAKE_AFFINE) {
  1067. unsigned long tl = this_load;
  1068. /*
  1069. * If sync wakeup then subtract the (maximum possible)
  1070. * effect of the currently running task from the load
  1071. * of the current CPU:
  1072. */
  1073. if (sync)
  1074. tl -= SCHED_LOAD_SCALE;
  1075. if ((tl <= load &&
  1076. tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
  1077. 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
  1078. /*
  1079. * This domain has SD_WAKE_AFFINE and
  1080. * p is cache cold in this domain, and
  1081. * there is no bad imbalance.
  1082. */
  1083. schedstat_inc(this_sd, ttwu_move_affine);
  1084. goto out_set_cpu;
  1085. }
  1086. }
  1087. /*
  1088. * Start passive balancing when half the imbalance_pct
  1089. * limit is reached.
  1090. */
  1091. if (this_sd->flags & SD_WAKE_BALANCE) {
  1092. if (imbalance*this_load <= 100*load) {
  1093. schedstat_inc(this_sd, ttwu_move_balance);
  1094. goto out_set_cpu;
  1095. }
  1096. }
  1097. }
  1098. new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
  1099. out_set_cpu:
  1100. new_cpu = wake_idle(new_cpu, p);
  1101. if (new_cpu != cpu) {
  1102. set_task_cpu(p, new_cpu);
  1103. task_rq_unlock(rq, &flags);
  1104. /* might preempt at this point */
  1105. rq = task_rq_lock(p, &flags);
  1106. old_state = p->state;
  1107. if (!(old_state & state))
  1108. goto out;
  1109. if (p->array)
  1110. goto out_running;
  1111. this_cpu = smp_processor_id();
  1112. cpu = task_cpu(p);
  1113. }
  1114. out_activate:
  1115. #endif /* CONFIG_SMP */
  1116. if (old_state == TASK_UNINTERRUPTIBLE) {
  1117. rq->nr_uninterruptible--;
  1118. /*
  1119. * Tasks on involuntary sleep don't earn
  1120. * sleep_avg beyond just interactive state.
  1121. */
  1122. p->activated = -1;
  1123. }
  1124. /*
  1125. * Tasks that have marked their sleep as noninteractive get
  1126. * woken up without updating their sleep average. (i.e. their
  1127. * sleep is handled in a priority-neutral manner, no priority
  1128. * boost and no penalty.)
  1129. */
  1130. if (old_state & TASK_NONINTERACTIVE)
  1131. __activate_task(p, rq);
  1132. else
  1133. activate_task(p, rq, cpu == this_cpu);
  1134. /*
  1135. * Sync wakeups (i.e. those types of wakeups where the waker
  1136. * has indicated that it will leave the CPU in short order)
  1137. * don't trigger a preemption, if the woken up task will run on
  1138. * this cpu. (in this case the 'I will reschedule' promise of
  1139. * the waker guarantees that the freshly woken up task is going
  1140. * to be considered on this CPU.)
  1141. */
  1142. if (!sync || cpu != this_cpu) {
  1143. if (TASK_PREEMPTS_CURR(p, rq))
  1144. resched_task(rq->curr);
  1145. }
  1146. success = 1;
  1147. out_running:
  1148. p->state = TASK_RUNNING;
  1149. out:
  1150. task_rq_unlock(rq, &flags);
  1151. return success;
  1152. }
  1153. int fastcall wake_up_process(task_t *p)
  1154. {
  1155. return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
  1156. TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
  1157. }
  1158. EXPORT_SYMBOL(wake_up_process);
  1159. int fastcall wake_up_state(task_t *p, unsigned int state)
  1160. {
  1161. return try_to_wake_up(p, state, 0);
  1162. }
  1163. /*
  1164. * Perform scheduler related setup for a newly forked process p.
  1165. * p is forked by current.
  1166. */
  1167. void fastcall sched_fork(task_t *p, int clone_flags)
  1168. {
  1169. int cpu = get_cpu();
  1170. #ifdef CONFIG_SMP
  1171. cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
  1172. #endif
  1173. set_task_cpu(p, cpu);
  1174. /*
  1175. * We mark the process as running here, but have not actually
  1176. * inserted it onto the runqueue yet. This guarantees that
  1177. * nobody will actually run it, and a signal or other external
  1178. * event cannot wake it up and insert it on the runqueue either.
  1179. */
  1180. p->state = TASK_RUNNING;
  1181. INIT_LIST_HEAD(&p->run_list);
  1182. p->array = NULL;
  1183. #ifdef CONFIG_SCHEDSTATS
  1184. memset(&p->sched_info, 0, sizeof(p->sched_info));
  1185. #endif
  1186. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  1187. p->oncpu = 0;
  1188. #endif
  1189. #ifdef CONFIG_PREEMPT
  1190. /* Want to start with kernel preemption disabled. */
  1191. task_thread_info(p)->preempt_count = 1;
  1192. #endif
  1193. /*
  1194. * Share the timeslice between parent and child, thus the
  1195. * total amount of pending timeslices in the system doesn't change,
  1196. * resulting in more scheduling fairness.
  1197. */
  1198. local_irq_disable();
  1199. p->time_slice = (current->time_slice + 1) >> 1;
  1200. /*
  1201. * The remainder of the first timeslice might be recovered by
  1202. * the parent if the child exits early enough.
  1203. */
  1204. p->first_time_slice = 1;
  1205. current->time_slice >>= 1;
  1206. p->timestamp = sched_clock();
  1207. if (unlikely(!current->time_slice)) {
  1208. /*
  1209. * This case is rare, it happens when the parent has only
  1210. * a single jiffy left from its timeslice. Taking the
  1211. * runqueue lock is not a problem.
  1212. */
  1213. current->time_slice = 1;
  1214. scheduler_tick();
  1215. }
  1216. local_irq_enable();
  1217. put_cpu();
  1218. }
  1219. /*
  1220. * wake_up_new_task - wake up a newly created task for the first time.
  1221. *
  1222. * This function will do some initial scheduler statistics housekeeping
  1223. * that must be done for every newly created context, then puts the task
  1224. * on the runqueue and wakes it.
  1225. */
  1226. void fastcall wake_up_new_task(task_t *p, unsigned long clone_flags)
  1227. {
  1228. unsigned long flags;
  1229. int this_cpu, cpu;
  1230. runqueue_t *rq, *this_rq;
  1231. rq = task_rq_lock(p, &flags);
  1232. BUG_ON(p->state != TASK_RUNNING);
  1233. this_cpu = smp_processor_id();
  1234. cpu = task_cpu(p);
  1235. /*
  1236. * We decrease the sleep average of forking parents
  1237. * and children as well, to keep max-interactive tasks
  1238. * from forking tasks that are max-interactive. The parent
  1239. * (current) is done further down, under its lock.
  1240. */
  1241. p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
  1242. CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1243. p->prio = effective_prio(p);
  1244. if (likely(cpu == this_cpu)) {
  1245. if (!(clone_flags & CLONE_VM)) {
  1246. /*
  1247. * The VM isn't cloned, so we're in a good position to
  1248. * do child-runs-first in anticipation of an exec. This
  1249. * usually avoids a lot of COW overhead.
  1250. */
  1251. if (unlikely(!current->array))
  1252. __activate_task(p, rq);
  1253. else {
  1254. p->prio = current->prio;
  1255. list_add_tail(&p->run_list, &current->run_list);
  1256. p->array = current->array;
  1257. p->array->nr_active++;
  1258. rq->nr_running++;
  1259. }
  1260. set_need_resched();
  1261. } else
  1262. /* Run child last */
  1263. __activate_task(p, rq);
  1264. /*
  1265. * We skip the following code due to cpu == this_cpu
  1266. *
  1267. * task_rq_unlock(rq, &flags);
  1268. * this_rq = task_rq_lock(current, &flags);
  1269. */
  1270. this_rq = rq;
  1271. } else {
  1272. this_rq = cpu_rq(this_cpu);
  1273. /*
  1274. * Not the local CPU - must adjust timestamp. This should
  1275. * get optimised away in the !CONFIG_SMP case.
  1276. */
  1277. p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
  1278. + rq->timestamp_last_tick;
  1279. __activate_task(p, rq);
  1280. if (TASK_PREEMPTS_CURR(p, rq))
  1281. resched_task(rq->curr);
  1282. /*
  1283. * Parent and child are on different CPUs, now get the
  1284. * parent runqueue to update the parent's ->sleep_avg:
  1285. */
  1286. task_rq_unlock(rq, &flags);
  1287. this_rq = task_rq_lock(current, &flags);
  1288. }
  1289. current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
  1290. PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1291. task_rq_unlock(this_rq, &flags);
  1292. }
  1293. /*
  1294. * Potentially available exiting-child timeslices are
  1295. * retrieved here - this way the parent does not get
  1296. * penalized for creating too many threads.
  1297. *
  1298. * (this cannot be used to 'generate' timeslices
  1299. * artificially, because any timeslice recovered here
  1300. * was given away by the parent in the first place.)
  1301. */
  1302. void fastcall sched_exit(task_t *p)
  1303. {
  1304. unsigned long flags;
  1305. runqueue_t *rq;
  1306. /*
  1307. * If the child was a (relative-) CPU hog then decrease
  1308. * the sleep_avg of the parent as well.
  1309. */
  1310. rq = task_rq_lock(p->parent, &flags);
  1311. if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
  1312. p->parent->time_slice += p->time_slice;
  1313. if (unlikely(p->parent->time_slice > task_timeslice(p)))
  1314. p->parent->time_slice = task_timeslice(p);
  1315. }
  1316. if (p->sleep_avg < p->parent->sleep_avg)
  1317. p->parent->sleep_avg = p->parent->sleep_avg /
  1318. (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
  1319. (EXIT_WEIGHT + 1);
  1320. task_rq_unlock(rq, &flags);
  1321. }
  1322. /**
  1323. * prepare_task_switch - prepare to switch tasks
  1324. * @rq: the runqueue preparing to switch
  1325. * @next: the task we are going to switch to.
  1326. *
  1327. * This is called with the rq lock held and interrupts off. It must
  1328. * be paired with a subsequent finish_task_switch after the context
  1329. * switch.
  1330. *
  1331. * prepare_task_switch sets up locking and calls architecture specific
  1332. * hooks.
  1333. */
  1334. static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
  1335. {
  1336. prepare_lock_switch(rq, next);
  1337. prepare_arch_switch(next);
  1338. }
  1339. /**
  1340. * finish_task_switch - clean up after a task-switch
  1341. * @rq: runqueue associated with task-switch
  1342. * @prev: the thread we just switched away from.
  1343. *
  1344. * finish_task_switch must be called after the context switch, paired
  1345. * with a prepare_task_switch call before the context switch.
  1346. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  1347. * and do any other architecture-specific cleanup actions.
  1348. *
  1349. * Note that we may have delayed dropping an mm in context_switch(). If
  1350. * so, we finish that here outside of the runqueue lock. (Doing it
  1351. * with the lock held can cause deadlocks; see schedule() for
  1352. * details.)
  1353. */
  1354. static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
  1355. __releases(rq->lock)
  1356. {
  1357. struct mm_struct *mm = rq->prev_mm;
  1358. unsigned long prev_task_flags;
  1359. rq->prev_mm = NULL;
  1360. /*
  1361. * A task struct has one reference for the use as "current".
  1362. * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
  1363. * calls schedule one last time. The schedule call will never return,
  1364. * and the scheduled task must drop that reference.
  1365. * The test for EXIT_ZOMBIE must occur while the runqueue locks are
  1366. * still held, otherwise prev could be scheduled on another cpu, die
  1367. * there before we look at prev->state, and then the reference would
  1368. * be dropped twice.
  1369. * Manfred Spraul <manfred@colorfullife.com>
  1370. */
  1371. prev_task_flags = prev->flags;
  1372. finish_arch_switch(prev);
  1373. finish_lock_switch(rq, prev);
  1374. if (mm)
  1375. mmdrop(mm);
  1376. if (unlikely(prev_task_flags & PF_DEAD))
  1377. put_task_struct(prev);
  1378. }
  1379. /**
  1380. * schedule_tail - first thing a freshly forked thread must call.
  1381. * @prev: the thread we just switched away from.
  1382. */
  1383. asmlinkage void schedule_tail(task_t *prev)
  1384. __releases(rq->lock)
  1385. {
  1386. runqueue_t *rq = this_rq();
  1387. finish_task_switch(rq, prev);
  1388. #ifdef __ARCH_WANT_UNLOCKED_CTXSW
  1389. /* In this case, finish_task_switch does not reenable preemption */
  1390. preempt_enable();
  1391. #endif
  1392. if (current->set_child_tid)
  1393. put_user(current->pid, current->set_child_tid);
  1394. }
  1395. /*
  1396. * context_switch - switch to the new MM and the new
  1397. * thread's register state.
  1398. */
  1399. static inline
  1400. task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
  1401. {
  1402. struct mm_struct *mm = next->mm;
  1403. struct mm_struct *oldmm = prev->active_mm;
  1404. if (unlikely(!mm)) {
  1405. next->active_mm = oldmm;
  1406. atomic_inc(&oldmm->mm_count);
  1407. enter_lazy_tlb(oldmm, next);
  1408. } else
  1409. switch_mm(oldmm, mm, next);
  1410. if (unlikely(!prev->mm)) {
  1411. prev->active_mm = NULL;
  1412. WARN_ON(rq->prev_mm);
  1413. rq->prev_mm = oldmm;
  1414. }
  1415. /* Here we just switch the register state and the stack. */
  1416. switch_to(prev, next, prev);
  1417. return prev;
  1418. }
  1419. /*
  1420. * nr_running, nr_uninterruptible and nr_context_switches:
  1421. *
  1422. * externally visible scheduler statistics: current number of runnable
  1423. * threads, current number of uninterruptible-sleeping threads, total
  1424. * number of context switches performed since bootup.
  1425. */
  1426. unsigned long nr_running(void)
  1427. {
  1428. unsigned long i, sum = 0;
  1429. for_each_online_cpu(i)
  1430. sum += cpu_rq(i)->nr_running;
  1431. return sum;
  1432. }
  1433. unsigned long nr_uninterruptible(void)
  1434. {
  1435. unsigned long i, sum = 0;
  1436. for_each_cpu(i)
  1437. sum += cpu_rq(i)->nr_uninterruptible;
  1438. /*
  1439. * Since we read the counters lockless, it might be slightly
  1440. * inaccurate. Do not allow it to go below zero though:
  1441. */
  1442. if (unlikely((long)sum < 0))
  1443. sum = 0;
  1444. return sum;
  1445. }
  1446. unsigned long long nr_context_switches(void)
  1447. {
  1448. unsigned long long i, sum = 0;
  1449. for_each_cpu(i)
  1450. sum += cpu_rq(i)->nr_switches;
  1451. return sum;
  1452. }
  1453. unsigned long nr_iowait(void)
  1454. {
  1455. unsigned long i, sum = 0;
  1456. for_each_cpu(i)
  1457. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  1458. return sum;
  1459. }
  1460. #ifdef CONFIG_SMP
  1461. /*
  1462. * double_rq_lock - safely lock two runqueues
  1463. *
  1464. * Note this does not disable interrupts like task_rq_lock,
  1465. * you need to do so manually before calling.
  1466. */
  1467. static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
  1468. __acquires(rq1->lock)
  1469. __acquires(rq2->lock)
  1470. {
  1471. if (rq1 == rq2) {
  1472. spin_lock(&rq1->lock);
  1473. __acquire(rq2->lock); /* Fake it out ;) */
  1474. } else {
  1475. if (rq1 < rq2) {
  1476. spin_lock(&rq1->lock);
  1477. spin_lock(&rq2->lock);
  1478. } else {
  1479. spin_lock(&rq2->lock);
  1480. spin_lock(&rq1->lock);
  1481. }
  1482. }
  1483. }
  1484. /*
  1485. * double_rq_unlock - safely unlock two runqueues
  1486. *
  1487. * Note this does not restore interrupts like task_rq_unlock,
  1488. * you need to do so manually after calling.
  1489. */
  1490. static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
  1491. __releases(rq1->lock)
  1492. __releases(rq2->lock)
  1493. {
  1494. spin_unlock(&rq1->lock);
  1495. if (rq1 != rq2)
  1496. spin_unlock(&rq2->lock);
  1497. else
  1498. __release(rq2->lock);
  1499. }
  1500. /*
  1501. * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
  1502. */
  1503. static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
  1504. __releases(this_rq->lock)
  1505. __acquires(busiest->lock)
  1506. __acquires(this_rq->lock)
  1507. {
  1508. if (unlikely(!spin_trylock(&busiest->lock))) {
  1509. if (busiest < this_rq) {
  1510. spin_unlock(&this_rq->lock);
  1511. spin_lock(&busiest->lock);
  1512. spin_lock(&this_rq->lock);
  1513. } else
  1514. spin_lock(&busiest->lock);
  1515. }
  1516. }
  1517. /*
  1518. * If dest_cpu is allowed for this process, migrate the task to it.
  1519. * This is accomplished by forcing the cpu_allowed mask to only
  1520. * allow dest_cpu, which will force the cpu onto dest_cpu. Then
  1521. * the cpu_allowed mask is restored.
  1522. */
  1523. static void sched_migrate_task(task_t *p, int dest_cpu)
  1524. {
  1525. migration_req_t req;
  1526. runqueue_t *rq;
  1527. unsigned long flags;
  1528. rq = task_rq_lock(p, &flags);
  1529. if (!cpu_isset(dest_cpu, p->cpus_allowed)
  1530. || unlikely(cpu_is_offline(dest_cpu)))
  1531. goto out;
  1532. /* force the process onto the specified CPU */
  1533. if (migrate_task(p, dest_cpu, &req)) {
  1534. /* Need to wait for migration thread (might exit: take ref). */
  1535. struct task_struct *mt = rq->migration_thread;
  1536. get_task_struct(mt);
  1537. task_rq_unlock(rq, &flags);
  1538. wake_up_process(mt);
  1539. put_task_struct(mt);
  1540. wait_for_completion(&req.done);
  1541. return;
  1542. }
  1543. out:
  1544. task_rq_unlock(rq, &flags);
  1545. }
  1546. /*
  1547. * sched_exec - execve() is a valuable balancing opportunity, because at
  1548. * this point the task has the smallest effective memory and cache footprint.
  1549. */
  1550. void sched_exec(void)
  1551. {
  1552. int new_cpu, this_cpu = get_cpu();
  1553. new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
  1554. put_cpu();
  1555. if (new_cpu != this_cpu)
  1556. sched_migrate_task(current, new_cpu);
  1557. }
  1558. /*
  1559. * pull_task - move a task from a remote runqueue to the local runqueue.
  1560. * Both runqueues must be locked.
  1561. */
  1562. static
  1563. void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
  1564. runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
  1565. {
  1566. dequeue_task(p, src_array);
  1567. src_rq->nr_running--;
  1568. set_task_cpu(p, this_cpu);
  1569. this_rq->nr_running++;
  1570. enqueue_task(p, this_array);
  1571. p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
  1572. + this_rq->timestamp_last_tick;
  1573. /*
  1574. * Note that idle threads have a prio of MAX_PRIO, for this test
  1575. * to be always true for them.
  1576. */
  1577. if (TASK_PREEMPTS_CURR(p, this_rq))
  1578. resched_task(this_rq->curr);
  1579. }
  1580. /*
  1581. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  1582. */
  1583. static
  1584. int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
  1585. struct sched_domain *sd, enum idle_type idle,
  1586. int *all_pinned)
  1587. {
  1588. /*
  1589. * We do not migrate tasks that are:
  1590. * 1) running (obviously), or
  1591. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  1592. * 3) are cache-hot on their current CPU.
  1593. */
  1594. if (!cpu_isset(this_cpu, p->cpus_allowed))
  1595. return 0;
  1596. *all_pinned = 0;
  1597. if (task_running(rq, p))
  1598. return 0;
  1599. /*
  1600. * Aggressive migration if:
  1601. * 1) task is cache cold, or
  1602. * 2) too many balance attempts have failed.
  1603. */
  1604. if (sd->nr_balance_failed > sd->cache_nice_tries)
  1605. return 1;
  1606. if (task_hot(p, rq->timestamp_last_tick, sd))
  1607. return 0;
  1608. return 1;
  1609. }
  1610. /*
  1611. * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
  1612. * as part of a balancing operation within "domain". Returns the number of
  1613. * tasks moved.
  1614. *
  1615. * Called with both runqueues locked.
  1616. */
  1617. static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
  1618. unsigned long max_nr_move, struct sched_domain *sd,
  1619. enum idle_type idle, int *all_pinned)
  1620. {
  1621. prio_array_t *array, *dst_array;
  1622. struct list_head *head, *curr;
  1623. int idx, pulled = 0, pinned = 0;
  1624. task_t *tmp;
  1625. if (max_nr_move == 0)
  1626. goto out;
  1627. pinned = 1;
  1628. /*
  1629. * We first consider expired tasks. Those will likely not be
  1630. * executed in the near future, and they are most likely to
  1631. * be cache-cold, thus switching CPUs has the least effect
  1632. * on them.
  1633. */
  1634. if (busiest->expired->nr_active) {
  1635. array = busiest->expired;
  1636. dst_array = this_rq->expired;
  1637. } else {
  1638. array = busiest->active;
  1639. dst_array = this_rq->active;
  1640. }
  1641. new_array:
  1642. /* Start searching at priority 0: */
  1643. idx = 0;
  1644. skip_bitmap:
  1645. if (!idx)
  1646. idx = sched_find_first_bit(array->bitmap);
  1647. else
  1648. idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
  1649. if (idx >= MAX_PRIO) {
  1650. if (array == busiest->expired && busiest->active->nr_active) {
  1651. array = busiest->active;
  1652. dst_array = this_rq->active;
  1653. goto new_array;
  1654. }
  1655. goto out;
  1656. }
  1657. head = array->queue + idx;
  1658. curr = head->prev;
  1659. skip_queue:
  1660. tmp = list_entry(curr, task_t, run_list);
  1661. curr = curr->prev;
  1662. if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
  1663. if (curr != head)
  1664. goto skip_queue;
  1665. idx++;
  1666. goto skip_bitmap;
  1667. }
  1668. #ifdef CONFIG_SCHEDSTATS
  1669. if (task_hot(tmp, busiest->timestamp_last_tick, sd))
  1670. schedstat_inc(sd, lb_hot_gained[idle]);
  1671. #endif
  1672. pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
  1673. pulled++;
  1674. /* We only want to steal up to the prescribed number of tasks. */
  1675. if (pulled < max_nr_move) {
  1676. if (curr != head)
  1677. goto skip_queue;
  1678. idx++;
  1679. goto skip_bitmap;
  1680. }
  1681. out:
  1682. /*
  1683. * Right now, this is the only place pull_task() is called,
  1684. * so we can safely collect pull_task() stats here rather than
  1685. * inside pull_task().
  1686. */
  1687. schedstat_add(sd, lb_gained[idle], pulled);
  1688. if (all_pinned)
  1689. *all_pinned = pinned;
  1690. return pulled;
  1691. }
  1692. /*
  1693. * find_busiest_group finds and returns the busiest CPU group within the
  1694. * domain. It calculates and returns the number of tasks which should be
  1695. * moved to restore balance via the imbalance parameter.
  1696. */
  1697. static struct sched_group *
  1698. find_busiest_group(struct sched_domain *sd, int this_cpu,
  1699. unsigned long *imbalance, enum idle_type idle, int *sd_idle)
  1700. {
  1701. struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
  1702. unsigned long max_load, avg_load, total_load, this_load, total_pwr;
  1703. unsigned long max_pull;
  1704. int load_idx;
  1705. max_load = this_load = total_load = total_pwr = 0;
  1706. if (idle == NOT_IDLE)
  1707. load_idx = sd->busy_idx;
  1708. else if (idle == NEWLY_IDLE)
  1709. load_idx = sd->newidle_idx;
  1710. else
  1711. load_idx = sd->idle_idx;
  1712. do {
  1713. unsigned long load;
  1714. int local_group;
  1715. int i;
  1716. local_group = cpu_isset(this_cpu, group->cpumask);
  1717. /* Tally up the load of all CPUs in the group */
  1718. avg_load = 0;
  1719. for_each_cpu_mask(i, group->cpumask) {
  1720. if (*sd_idle && !idle_cpu(i))
  1721. *sd_idle = 0;
  1722. /* Bias balancing toward cpus of our domain */
  1723. if (local_group)
  1724. load = target_load(i, load_idx);
  1725. else
  1726. load = source_load(i, load_idx);
  1727. avg_load += load;
  1728. }
  1729. total_load += avg_load;
  1730. total_pwr += group->cpu_power;
  1731. /* Adjust by relative CPU power of the group */
  1732. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  1733. if (local_group) {
  1734. this_load = avg_load;
  1735. this = group;
  1736. } else if (avg_load > max_load) {
  1737. max_load = avg_load;
  1738. busiest = group;
  1739. }
  1740. group = group->next;
  1741. } while (group != sd->groups);
  1742. if (!busiest || this_load >= max_load || max_load <= SCHED_LOAD_SCALE)
  1743. goto out_balanced;
  1744. avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
  1745. if (this_load >= avg_load ||
  1746. 100*max_load <= sd->imbalance_pct*this_load)
  1747. goto out_balanced;
  1748. /*
  1749. * We're trying to get all the cpus to the average_load, so we don't
  1750. * want to push ourselves above the average load, nor do we wish to
  1751. * reduce the max loaded cpu below the average load, as either of these
  1752. * actions would just result in more rebalancing later, and ping-pong
  1753. * tasks around. Thus we look for the minimum possible imbalance.
  1754. * Negative imbalances (*we* are more loaded than anyone else) will
  1755. * be counted as no imbalance for these purposes -- we can't fix that
  1756. * by pulling tasks to us. Be careful of negative numbers as they'll
  1757. * appear as very large values with unsigned longs.
  1758. */
  1759. /* Don't want to pull so many tasks that a group would go idle */
  1760. max_pull = min(max_load - avg_load, max_load - SCHED_LOAD_SCALE);
  1761. /* How much load to actually move to equalise the imbalance */
  1762. *imbalance = min(max_pull * busiest->cpu_power,
  1763. (avg_load - this_load) * this->cpu_power)
  1764. / SCHED_LOAD_SCALE;
  1765. if (*imbalance < SCHED_LOAD_SCALE) {
  1766. unsigned long pwr_now = 0, pwr_move = 0;
  1767. unsigned long tmp;
  1768. if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
  1769. *imbalance = 1;
  1770. return busiest;
  1771. }
  1772. /*
  1773. * OK, we don't have enough imbalance to justify moving tasks,
  1774. * however we may be able to increase total CPU power used by
  1775. * moving them.
  1776. */
  1777. pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
  1778. pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
  1779. pwr_now /= SCHED_LOAD_SCALE;
  1780. /* Amount of load we'd subtract */
  1781. tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
  1782. if (max_load > tmp)
  1783. pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
  1784. max_load - tmp);
  1785. /* Amount of load we'd add */
  1786. if (max_load*busiest->cpu_power <
  1787. SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
  1788. tmp = max_load*busiest->cpu_power/this->cpu_power;
  1789. else
  1790. tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
  1791. pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
  1792. pwr_move /= SCHED_LOAD_SCALE;
  1793. /* Move if we gain throughput */
  1794. if (pwr_move <= pwr_now)
  1795. goto out_balanced;
  1796. *imbalance = 1;
  1797. return busiest;
  1798. }
  1799. /* Get rid of the scaling factor, rounding down as we divide */
  1800. *imbalance = *imbalance / SCHED_LOAD_SCALE;
  1801. return busiest;
  1802. out_balanced:
  1803. *imbalance = 0;
  1804. return NULL;
  1805. }
  1806. /*
  1807. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  1808. */
  1809. static runqueue_t *find_busiest_queue(struct sched_group *group,
  1810. enum idle_type idle)
  1811. {
  1812. unsigned long load, max_load = 0;
  1813. runqueue_t *busiest = NULL;
  1814. int i;
  1815. for_each_cpu_mask(i, group->cpumask) {
  1816. load = source_load(i, 0);
  1817. if (load > max_load) {
  1818. max_load = load;
  1819. busiest = cpu_rq(i);
  1820. }
  1821. }
  1822. return busiest;
  1823. }
  1824. /*
  1825. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  1826. * so long as it is large enough.
  1827. */
  1828. #define MAX_PINNED_INTERVAL 512
  1829. /*
  1830. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  1831. * tasks if there is an imbalance.
  1832. *
  1833. * Called with this_rq unlocked.
  1834. */
  1835. static int load_balance(int this_cpu, runqueue_t *this_rq,
  1836. struct sched_domain *sd, enum idle_type idle)
  1837. {
  1838. struct sched_group *group;
  1839. runqueue_t *busiest;
  1840. unsigned long imbalance;
  1841. int nr_moved, all_pinned = 0;
  1842. int active_balance = 0;
  1843. int sd_idle = 0;
  1844. if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER)
  1845. sd_idle = 1;
  1846. schedstat_inc(sd, lb_cnt[idle]);
  1847. group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
  1848. if (!group) {
  1849. schedstat_inc(sd, lb_nobusyg[idle]);
  1850. goto out_balanced;
  1851. }
  1852. busiest = find_busiest_queue(group, idle);
  1853. if (!busiest) {
  1854. schedstat_inc(sd, lb_nobusyq[idle]);
  1855. goto out_balanced;
  1856. }
  1857. BUG_ON(busiest == this_rq);
  1858. schedstat_add(sd, lb_imbalance[idle], imbalance);
  1859. nr_moved = 0;
  1860. if (busiest->nr_running > 1) {
  1861. /*
  1862. * Attempt to move tasks. If find_busiest_group has found
  1863. * an imbalance but busiest->nr_running <= 1, the group is
  1864. * still unbalanced. nr_moved simply stays zero, so it is
  1865. * correctly treated as an imbalance.
  1866. */
  1867. double_rq_lock(this_rq, busiest);
  1868. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  1869. imbalance, sd, idle, &all_pinned);
  1870. double_rq_unlock(this_rq, busiest);
  1871. /* All tasks on this runqueue were pinned by CPU affinity */
  1872. if (unlikely(all_pinned))
  1873. goto out_balanced;
  1874. }
  1875. if (!nr_moved) {
  1876. schedstat_inc(sd, lb_failed[idle]);
  1877. sd->nr_balance_failed++;
  1878. if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
  1879. spin_lock(&busiest->lock);
  1880. /* don't kick the migration_thread, if the curr
  1881. * task on busiest cpu can't be moved to this_cpu
  1882. */
  1883. if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
  1884. spin_unlock(&busiest->lock);
  1885. all_pinned = 1;
  1886. goto out_one_pinned;
  1887. }
  1888. if (!busiest->active_balance) {
  1889. busiest->active_balance = 1;
  1890. busiest->push_cpu = this_cpu;
  1891. active_balance = 1;
  1892. }
  1893. spin_unlock(&busiest->lock);
  1894. if (active_balance)
  1895. wake_up_process(busiest->migration_thread);
  1896. /*
  1897. * We've kicked active balancing, reset the failure
  1898. * counter.
  1899. */
  1900. sd->nr_balance_failed = sd->cache_nice_tries+1;
  1901. }
  1902. } else
  1903. sd->nr_balance_failed = 0;
  1904. if (likely(!active_balance)) {
  1905. /* We were unbalanced, so reset the balancing interval */
  1906. sd->balance_interval = sd->min_interval;
  1907. } else {
  1908. /*
  1909. * If we've begun active balancing, start to back off. This
  1910. * case may not be covered by the all_pinned logic if there
  1911. * is only 1 task on the busy runqueue (because we don't call
  1912. * move_tasks).
  1913. */
  1914. if (sd->balance_interval < sd->max_interval)
  1915. sd->balance_interval *= 2;
  1916. }
  1917. if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1918. return -1;
  1919. return nr_moved;
  1920. out_balanced:
  1921. schedstat_inc(sd, lb_balanced[idle]);
  1922. sd->nr_balance_failed = 0;
  1923. out_one_pinned:
  1924. /* tune up the balancing interval */
  1925. if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
  1926. (sd->balance_interval < sd->max_interval))
  1927. sd->balance_interval *= 2;
  1928. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1929. return -1;
  1930. return 0;
  1931. }
  1932. /*
  1933. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  1934. * tasks if there is an imbalance.
  1935. *
  1936. * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
  1937. * this_rq is locked.
  1938. */
  1939. static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
  1940. struct sched_domain *sd)
  1941. {
  1942. struct sched_group *group;
  1943. runqueue_t *busiest = NULL;
  1944. unsigned long imbalance;
  1945. int nr_moved = 0;
  1946. int sd_idle = 0;
  1947. if (sd->flags & SD_SHARE_CPUPOWER)
  1948. sd_idle = 1;
  1949. schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
  1950. group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
  1951. if (!group) {
  1952. schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
  1953. goto out_balanced;
  1954. }
  1955. busiest = find_busiest_queue(group, NEWLY_IDLE);
  1956. if (!busiest) {
  1957. schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
  1958. goto out_balanced;
  1959. }
  1960. BUG_ON(busiest == this_rq);
  1961. schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
  1962. nr_moved = 0;
  1963. if (busiest->nr_running > 1) {
  1964. /* Attempt to move tasks */
  1965. double_lock_balance(this_rq, busiest);
  1966. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  1967. imbalance, sd, NEWLY_IDLE, NULL);
  1968. spin_unlock(&busiest->lock);
  1969. }
  1970. if (!nr_moved) {
  1971. schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
  1972. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1973. return -1;
  1974. } else
  1975. sd->nr_balance_failed = 0;
  1976. return nr_moved;
  1977. out_balanced:
  1978. schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
  1979. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1980. return -1;
  1981. sd->nr_balance_failed = 0;
  1982. return 0;
  1983. }
  1984. /*
  1985. * idle_balance is called by schedule() if this_cpu is about to become
  1986. * idle. Attempts to pull tasks from other CPUs.
  1987. */
  1988. static void idle_balance(int this_cpu, runqueue_t *this_rq)
  1989. {
  1990. struct sched_domain *sd;
  1991. for_each_domain(this_cpu, sd) {
  1992. if (sd->flags & SD_BALANCE_NEWIDLE) {
  1993. if (load_balance_newidle(this_cpu, this_rq, sd)) {
  1994. /* We've pulled tasks over so stop searching */
  1995. break;
  1996. }
  1997. }
  1998. }
  1999. }
  2000. /*
  2001. * active_load_balance is run by migration threads. It pushes running tasks
  2002. * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
  2003. * running on each physical CPU where possible, and avoids physical /
  2004. * logical imbalances.
  2005. *
  2006. * Called with busiest_rq locked.
  2007. */
  2008. static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
  2009. {
  2010. struct sched_domain *sd;
  2011. runqueue_t *target_rq;
  2012. int target_cpu = busiest_rq->push_cpu;
  2013. if (busiest_rq->nr_running <= 1)
  2014. /* no task to move */
  2015. return;
  2016. target_rq = cpu_rq(target_cpu);
  2017. /*
  2018. * This condition is "impossible", if it occurs
  2019. * we need to fix it. Originally reported by
  2020. * Bjorn Helgaas on a 128-cpu setup.
  2021. */
  2022. BUG_ON(busiest_rq == target_rq);
  2023. /* move a task from busiest_rq to target_rq */
  2024. double_lock_balance(busiest_rq, target_rq);
  2025. /* Search for an sd spanning us and the target CPU. */
  2026. for_each_domain(target_cpu, sd)
  2027. if ((sd->flags & SD_LOAD_BALANCE) &&
  2028. cpu_isset(busiest_cpu, sd->span))
  2029. break;
  2030. if (unlikely(sd == NULL))
  2031. goto out;
  2032. schedstat_inc(sd, alb_cnt);
  2033. if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
  2034. schedstat_inc(sd, alb_pushed);
  2035. else
  2036. schedstat_inc(sd, alb_failed);
  2037. out:
  2038. spin_unlock(&target_rq->lock);
  2039. }
  2040. /*
  2041. * rebalance_tick will get called every timer tick, on every CPU.
  2042. *
  2043. * It checks each scheduling domain to see if it is due to be balanced,
  2044. * and initiates a balancing operation if so.
  2045. *
  2046. * Balancing parameters are set up in arch_init_sched_domains.
  2047. */
  2048. /* Don't have all balancing operations going off at once */
  2049. #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
  2050. static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
  2051. enum idle_type idle)
  2052. {
  2053. unsigned long old_load, this_load;
  2054. unsigned long j = jiffies + CPU_OFFSET(this_cpu);
  2055. struct sched_domain *sd;
  2056. int i;
  2057. this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
  2058. /* Update our load */
  2059. for (i = 0; i < 3; i++) {
  2060. unsigned long new_load = this_load;
  2061. int scale = 1 << i;
  2062. old_load = this_rq->cpu_load[i];
  2063. /*
  2064. * Round up the averaging division if load is increasing. This
  2065. * prevents us from getting stuck on 9 if the load is 10, for
  2066. * example.
  2067. */
  2068. if (new_load > old_load)
  2069. new_load += scale-1;
  2070. this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
  2071. }
  2072. for_each_domain(this_cpu, sd) {
  2073. unsigned long interval;
  2074. if (!(sd->flags & SD_LOAD_BALANCE))
  2075. continue;
  2076. interval = sd->balance_interval;
  2077. if (idle != SCHED_IDLE)
  2078. interval *= sd->busy_factor;
  2079. /* scale ms to jiffies */
  2080. interval = msecs_to_jiffies(interval);
  2081. if (unlikely(!interval))
  2082. interval = 1;
  2083. if (j - sd->last_balance >= interval) {
  2084. if (load_balance(this_cpu, this_rq, sd, idle)) {
  2085. /*
  2086. * We've pulled tasks over so either we're no
  2087. * longer idle, or one of our SMT siblings is
  2088. * not idle.
  2089. */
  2090. idle = NOT_IDLE;
  2091. }
  2092. sd->last_balance += interval;
  2093. }
  2094. }
  2095. }
  2096. #else
  2097. /*
  2098. * on UP we do not need to balance between CPUs:
  2099. */
  2100. static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
  2101. {
  2102. }
  2103. static inline void idle_balance(int cpu, runqueue_t *rq)
  2104. {
  2105. }
  2106. #endif
  2107. static inline int wake_priority_sleeper(runqueue_t *rq)
  2108. {
  2109. int ret = 0;
  2110. #ifdef CONFIG_SCHED_SMT
  2111. spin_lock(&rq->lock);
  2112. /*
  2113. * If an SMT sibling task has been put to sleep for priority
  2114. * reasons reschedule the idle task to see if it can now run.
  2115. */
  2116. if (rq->nr_running) {
  2117. resched_task(rq->idle);
  2118. ret = 1;
  2119. }
  2120. spin_unlock(&rq->lock);
  2121. #endif
  2122. return ret;
  2123. }
  2124. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2125. EXPORT_PER_CPU_SYMBOL(kstat);
  2126. /*
  2127. * This is called on clock ticks and on context switches.
  2128. * Bank in p->sched_time the ns elapsed since the last tick or switch.
  2129. */
  2130. static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
  2131. unsigned long long now)
  2132. {
  2133. unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
  2134. p->sched_time += now - last;
  2135. }
  2136. /*
  2137. * Return current->sched_time plus any more ns on the sched_clock
  2138. * that have not yet been banked.
  2139. */
  2140. unsigned long long current_sched_time(const task_t *tsk)
  2141. {
  2142. unsigned long long ns;
  2143. unsigned long flags;
  2144. local_irq_save(flags);
  2145. ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
  2146. ns = tsk->sched_time + (sched_clock() - ns);
  2147. local_irq_restore(flags);
  2148. return ns;
  2149. }
  2150. /*
  2151. * We place interactive tasks back into the active array, if possible.
  2152. *
  2153. * To guarantee that this does not starve expired tasks we ignore the
  2154. * interactivity of a task if the first expired task had to wait more
  2155. * than a 'reasonable' amount of time. This deadline timeout is
  2156. * load-dependent, as the frequency of array switched decreases with
  2157. * increasing number of running tasks. We also ignore the interactivity
  2158. * if a better static_prio task has expired:
  2159. */
  2160. #define EXPIRED_STARVING(rq) \
  2161. ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
  2162. (jiffies - (rq)->expired_timestamp >= \
  2163. STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
  2164. ((rq)->curr->static_prio > (rq)->best_expired_prio))
  2165. /*
  2166. * Account user cpu time to a process.
  2167. * @p: the process that the cpu time gets accounted to
  2168. * @hardirq_offset: the offset to subtract from hardirq_count()
  2169. * @cputime: the cpu time spent in user space since the last update
  2170. */
  2171. void account_user_time(struct task_struct *p, cputime_t cputime)
  2172. {
  2173. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2174. cputime64_t tmp;
  2175. p->utime = cputime_add(p->utime, cputime);
  2176. /* Add user time to cpustat. */
  2177. tmp = cputime_to_cputime64(cputime);
  2178. if (TASK_NICE(p) > 0)
  2179. cpustat->nice = cputime64_add(cpustat->nice, tmp);
  2180. else
  2181. cpustat->user = cputime64_add(cpustat->user, tmp);
  2182. }
  2183. /*
  2184. * Account system cpu time to a process.
  2185. * @p: the process that the cpu time gets accounted to
  2186. * @hardirq_offset: the offset to subtract from hardirq_count()
  2187. * @cputime: the cpu time spent in kernel space since the last update
  2188. */
  2189. void account_system_time(struct task_struct *p, int hardirq_offset,
  2190. cputime_t cputime)
  2191. {
  2192. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2193. runqueue_t *rq = this_rq();
  2194. cputime64_t tmp;
  2195. p->stime = cputime_add(p->stime, cputime);
  2196. /* Add system time to cpustat. */
  2197. tmp = cputime_to_cputime64(cputime);
  2198. if (hardirq_count() - hardirq_offset)
  2199. cpustat->irq = cputime64_add(cpustat->irq, tmp);
  2200. else if (softirq_count())
  2201. cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
  2202. else if (p != rq->idle)
  2203. cpustat->system = cputime64_add(cpustat->system, tmp);
  2204. else if (atomic_read(&rq->nr_iowait) > 0)
  2205. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2206. else
  2207. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2208. /* Account for system time used */
  2209. acct_update_integrals(p);
  2210. }
  2211. /*
  2212. * Account for involuntary wait time.
  2213. * @p: the process from which the cpu time has been stolen
  2214. * @steal: the cpu time spent in involuntary wait
  2215. */
  2216. void account_steal_time(struct task_struct *p, cputime_t steal)
  2217. {
  2218. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2219. cputime64_t tmp = cputime_to_cputime64(steal);
  2220. runqueue_t *rq = this_rq();
  2221. if (p == rq->idle) {
  2222. p->stime = cputime_add(p->stime, steal);
  2223. if (atomic_read(&rq->nr_iowait) > 0)
  2224. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2225. else
  2226. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2227. } else
  2228. cpustat->steal = cputime64_add(cpustat->steal, tmp);
  2229. }
  2230. /*
  2231. * This function gets called by the timer code, with HZ frequency.
  2232. * We call it with interrupts disabled.
  2233. *
  2234. * It also gets called by the fork code, when changing the parent's
  2235. * timeslices.
  2236. */
  2237. void scheduler_tick(void)
  2238. {
  2239. int cpu = smp_processor_id();
  2240. runqueue_t *rq = this_rq();
  2241. task_t *p = current;
  2242. unsigned long long now = sched_clock();
  2243. update_cpu_clock(p, rq, now);
  2244. rq->timestamp_last_tick = now;
  2245. if (p == rq->idle) {
  2246. if (wake_priority_sleeper(rq))
  2247. goto out;
  2248. rebalance_tick(cpu, rq, SCHED_IDLE);
  2249. return;
  2250. }
  2251. /* Task might have expired already, but not scheduled off yet */
  2252. if (p->array != rq->active) {
  2253. set_tsk_need_resched(p);
  2254. goto out;
  2255. }
  2256. spin_lock(&rq->lock);
  2257. /*
  2258. * The task was running during this tick - update the
  2259. * time slice counter. Note: we do not update a thread's
  2260. * priority until it either goes to sleep or uses up its
  2261. * timeslice. This makes it possible for interactive tasks
  2262. * to use up their timeslices at their highest priority levels.
  2263. */
  2264. if (rt_task(p)) {
  2265. /*
  2266. * RR tasks need a special form of timeslice management.
  2267. * FIFO tasks have no timeslices.
  2268. */
  2269. if ((p->policy == SCHED_RR) && !--p->time_slice) {
  2270. p->time_slice = task_timeslice(p);
  2271. p->first_time_slice = 0;
  2272. set_tsk_need_resched(p);
  2273. /* put it at the end of the queue: */
  2274. requeue_task(p, rq->active);
  2275. }
  2276. goto out_unlock;
  2277. }
  2278. if (!--p->time_slice) {
  2279. dequeue_task(p, rq->active);
  2280. set_tsk_need_resched(p);
  2281. p->prio = effective_prio(p);
  2282. p->time_slice = task_timeslice(p);
  2283. p->first_time_slice = 0;
  2284. if (!rq->expired_timestamp)
  2285. rq->expired_timestamp = jiffies;
  2286. if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
  2287. enqueue_task(p, rq->expired);
  2288. if (p->static_prio < rq->best_expired_prio)
  2289. rq->best_expired_prio = p->static_prio;
  2290. } else
  2291. enqueue_task(p, rq->active);
  2292. } else {
  2293. /*
  2294. * Prevent a too long timeslice allowing a task to monopolize
  2295. * the CPU. We do this by splitting up the timeslice into
  2296. * smaller pieces.
  2297. *
  2298. * Note: this does not mean the task's timeslices expire or
  2299. * get lost in any way, they just might be preempted by
  2300. * another task of equal priority. (one with higher
  2301. * priority would have preempted this task already.) We
  2302. * requeue this task to the end of the list on this priority
  2303. * level, which is in essence a round-robin of tasks with
  2304. * equal priority.
  2305. *
  2306. * This only applies to tasks in the interactive
  2307. * delta range with at least TIMESLICE_GRANULARITY to requeue.
  2308. */
  2309. if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
  2310. p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
  2311. (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
  2312. (p->array == rq->active)) {
  2313. requeue_task(p, rq->active);
  2314. set_tsk_need_resched(p);
  2315. }
  2316. }
  2317. out_unlock:
  2318. spin_unlock(&rq->lock);
  2319. out:
  2320. rebalance_tick(cpu, rq, NOT_IDLE);
  2321. }
  2322. #ifdef CONFIG_SCHED_SMT
  2323. static inline void wakeup_busy_runqueue(runqueue_t *rq)
  2324. {
  2325. /* If an SMT runqueue is sleeping due to priority reasons wake it up */
  2326. if (rq->curr == rq->idle && rq->nr_running)
  2327. resched_task(rq->idle);
  2328. }
  2329. static void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
  2330. {
  2331. struct sched_domain *tmp, *sd = NULL;
  2332. cpumask_t sibling_map;
  2333. int i;
  2334. for_each_domain(this_cpu, tmp)
  2335. if (tmp->flags & SD_SHARE_CPUPOWER)
  2336. sd = tmp;
  2337. if (!sd)
  2338. return;
  2339. /*
  2340. * Unlock the current runqueue because we have to lock in
  2341. * CPU order to avoid deadlocks. Caller knows that we might
  2342. * unlock. We keep IRQs disabled.
  2343. */
  2344. spin_unlock(&this_rq->lock);
  2345. sibling_map = sd->span;
  2346. for_each_cpu_mask(i, sibling_map)
  2347. spin_lock(&cpu_rq(i)->lock);
  2348. /*
  2349. * We clear this CPU from the mask. This both simplifies the
  2350. * inner loop and keps this_rq locked when we exit:
  2351. */
  2352. cpu_clear(this_cpu, sibling_map);
  2353. for_each_cpu_mask(i, sibling_map) {
  2354. runqueue_t *smt_rq = cpu_rq(i);
  2355. wakeup_busy_runqueue(smt_rq);
  2356. }
  2357. for_each_cpu_mask(i, sibling_map)
  2358. spin_unlock(&cpu_rq(i)->lock);
  2359. /*
  2360. * We exit with this_cpu's rq still held and IRQs
  2361. * still disabled:
  2362. */
  2363. }
  2364. /*
  2365. * number of 'lost' timeslices this task wont be able to fully
  2366. * utilize, if another task runs on a sibling. This models the
  2367. * slowdown effect of other tasks running on siblings:
  2368. */
  2369. static inline unsigned long smt_slice(task_t *p, struct sched_domain *sd)
  2370. {
  2371. return p->time_slice * (100 - sd->per_cpu_gain) / 100;
  2372. }
  2373. static int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
  2374. {
  2375. struct sched_domain *tmp, *sd = NULL;
  2376. cpumask_t sibling_map;
  2377. prio_array_t *array;
  2378. int ret = 0, i;
  2379. task_t *p;
  2380. for_each_domain(this_cpu, tmp)
  2381. if (tmp->flags & SD_SHARE_CPUPOWER)
  2382. sd = tmp;
  2383. if (!sd)
  2384. return 0;
  2385. /*
  2386. * The same locking rules and details apply as for
  2387. * wake_sleeping_dependent():
  2388. */
  2389. spin_unlock(&this_rq->lock);
  2390. sibling_map = sd->span;
  2391. for_each_cpu_mask(i, sibling_map)
  2392. spin_lock(&cpu_rq(i)->lock);
  2393. cpu_clear(this_cpu, sibling_map);
  2394. /*
  2395. * Establish next task to be run - it might have gone away because
  2396. * we released the runqueue lock above:
  2397. */
  2398. if (!this_rq->nr_running)
  2399. goto out_unlock;
  2400. array = this_rq->active;
  2401. if (!array->nr_active)
  2402. array = this_rq->expired;
  2403. BUG_ON(!array->nr_active);
  2404. p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
  2405. task_t, run_list);
  2406. for_each_cpu_mask(i, sibling_map) {
  2407. runqueue_t *smt_rq = cpu_rq(i);
  2408. task_t *smt_curr = smt_rq->curr;
  2409. /* Kernel threads do not participate in dependent sleeping */
  2410. if (!p->mm || !smt_curr->mm || rt_task(p))
  2411. goto check_smt_task;
  2412. /*
  2413. * If a user task with lower static priority than the
  2414. * running task on the SMT sibling is trying to schedule,
  2415. * delay it till there is proportionately less timeslice
  2416. * left of the sibling task to prevent a lower priority
  2417. * task from using an unfair proportion of the
  2418. * physical cpu's resources. -ck
  2419. */
  2420. if (rt_task(smt_curr)) {
  2421. /*
  2422. * With real time tasks we run non-rt tasks only
  2423. * per_cpu_gain% of the time.
  2424. */
  2425. if ((jiffies % DEF_TIMESLICE) >
  2426. (sd->per_cpu_gain * DEF_TIMESLICE / 100))
  2427. ret = 1;
  2428. } else
  2429. if (smt_curr->static_prio < p->static_prio &&
  2430. !TASK_PREEMPTS_CURR(p, smt_rq) &&
  2431. smt_slice(smt_curr, sd) > task_timeslice(p))
  2432. ret = 1;
  2433. check_smt_task:
  2434. if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
  2435. rt_task(smt_curr))
  2436. continue;
  2437. if (!p->mm) {
  2438. wakeup_busy_runqueue(smt_rq);
  2439. continue;
  2440. }
  2441. /*
  2442. * Reschedule a lower priority task on the SMT sibling for
  2443. * it to be put to sleep, or wake it up if it has been put to
  2444. * sleep for priority reasons to see if it should run now.
  2445. */
  2446. if (rt_task(p)) {
  2447. if ((jiffies % DEF_TIMESLICE) >
  2448. (sd->per_cpu_gain * DEF_TIMESLICE / 100))
  2449. resched_task(smt_curr);
  2450. } else {
  2451. if (TASK_PREEMPTS_CURR(p, smt_rq) &&
  2452. smt_slice(p, sd) > task_timeslice(smt_curr))
  2453. resched_task(smt_curr);
  2454. else
  2455. wakeup_busy_runqueue(smt_rq);
  2456. }
  2457. }
  2458. out_unlock:
  2459. for_each_cpu_mask(i, sibling_map)
  2460. spin_unlock(&cpu_rq(i)->lock);
  2461. return ret;
  2462. }
  2463. #else
  2464. static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
  2465. {
  2466. }
  2467. static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
  2468. {
  2469. return 0;
  2470. }
  2471. #endif
  2472. #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
  2473. void fastcall add_preempt_count(int val)
  2474. {
  2475. /*
  2476. * Underflow?
  2477. */
  2478. BUG_ON((preempt_count() < 0));
  2479. preempt_count() += val;
  2480. /*
  2481. * Spinlock count overflowing soon?
  2482. */
  2483. BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
  2484. }
  2485. EXPORT_SYMBOL(add_preempt_count);
  2486. void fastcall sub_preempt_count(int val)
  2487. {
  2488. /*
  2489. * Underflow?
  2490. */
  2491. BUG_ON(val > preempt_count());
  2492. /*
  2493. * Is the spinlock portion underflowing?
  2494. */
  2495. BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
  2496. preempt_count() -= val;
  2497. }
  2498. EXPORT_SYMBOL(sub_preempt_count);
  2499. #endif
  2500. /*
  2501. * schedule() is the main scheduler function.
  2502. */
  2503. asmlinkage void __sched schedule(void)
  2504. {
  2505. long *switch_count;
  2506. task_t *prev, *next;
  2507. runqueue_t *rq;
  2508. prio_array_t *array;
  2509. struct list_head *queue;
  2510. unsigned long long now;
  2511. unsigned long run_time;
  2512. int cpu, idx, new_prio;
  2513. /*
  2514. * Test if we are atomic. Since do_exit() needs to call into
  2515. * schedule() atomically, we ignore that path for now.
  2516. * Otherwise, whine if we are scheduling when we should not be.
  2517. */
  2518. if (likely(!current->exit_state)) {
  2519. if (unlikely(in_atomic())) {
  2520. printk(KERN_ERR "scheduling while atomic: "
  2521. "%s/0x%08x/%d\n",
  2522. current->comm, preempt_count(), current->pid);
  2523. dump_stack();
  2524. }
  2525. }
  2526. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2527. need_resched:
  2528. preempt_disable();
  2529. prev = current;
  2530. release_kernel_lock(prev);
  2531. need_resched_nonpreemptible:
  2532. rq = this_rq();
  2533. /*
  2534. * The idle thread is not allowed to schedule!
  2535. * Remove this check after it has been exercised a bit.
  2536. */
  2537. if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
  2538. printk(KERN_ERR "bad: scheduling from the idle thread!\n");
  2539. dump_stack();
  2540. }
  2541. schedstat_inc(rq, sched_cnt);
  2542. now = sched_clock();
  2543. if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
  2544. run_time = now - prev->timestamp;
  2545. if (unlikely((long long)(now - prev->timestamp) < 0))
  2546. run_time = 0;
  2547. } else
  2548. run_time = NS_MAX_SLEEP_AVG;
  2549. /*
  2550. * Tasks charged proportionately less run_time at high sleep_avg to
  2551. * delay them losing their interactive status
  2552. */
  2553. run_time /= (CURRENT_BONUS(prev) ? : 1);
  2554. spin_lock_irq(&rq->lock);
  2555. if (unlikely(prev->flags & PF_DEAD))
  2556. prev->state = EXIT_DEAD;
  2557. switch_count = &prev->nivcsw;
  2558. if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
  2559. switch_count = &prev->nvcsw;
  2560. if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
  2561. unlikely(signal_pending(prev))))
  2562. prev->state = TASK_RUNNING;
  2563. else {
  2564. if (prev->state == TASK_UNINTERRUPTIBLE)
  2565. rq->nr_uninterruptible++;
  2566. deactivate_task(prev, rq);
  2567. }
  2568. }
  2569. cpu = smp_processor_id();
  2570. if (unlikely(!rq->nr_running)) {
  2571. go_idle:
  2572. idle_balance(cpu, rq);
  2573. if (!rq->nr_running) {
  2574. next = rq->idle;
  2575. rq->expired_timestamp = 0;
  2576. wake_sleeping_dependent(cpu, rq);
  2577. /*
  2578. * wake_sleeping_dependent() might have released
  2579. * the runqueue, so break out if we got new
  2580. * tasks meanwhile:
  2581. */
  2582. if (!rq->nr_running)
  2583. goto switch_tasks;
  2584. }
  2585. } else {
  2586. if (dependent_sleeper(cpu, rq)) {
  2587. next = rq->idle;
  2588. goto switch_tasks;
  2589. }
  2590. /*
  2591. * dependent_sleeper() releases and reacquires the runqueue
  2592. * lock, hence go into the idle loop if the rq went
  2593. * empty meanwhile:
  2594. */
  2595. if (unlikely(!rq->nr_running))
  2596. goto go_idle;
  2597. }
  2598. array = rq->active;
  2599. if (unlikely(!array->nr_active)) {
  2600. /*
  2601. * Switch the active and expired arrays.
  2602. */
  2603. schedstat_inc(rq, sched_switch);
  2604. rq->active = rq->expired;
  2605. rq->expired = array;
  2606. array = rq->active;
  2607. rq->expired_timestamp = 0;
  2608. rq->best_expired_prio = MAX_PRIO;
  2609. }
  2610. idx = sched_find_first_bit(array->bitmap);
  2611. queue = array->queue + idx;
  2612. next = list_entry(queue->next, task_t, run_list);
  2613. if (!rt_task(next) && next->activated > 0) {
  2614. unsigned long long delta = now - next->timestamp;
  2615. if (unlikely((long long)(now - next->timestamp) < 0))
  2616. delta = 0;
  2617. if (next->activated == 1)
  2618. delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
  2619. array = next->array;
  2620. new_prio = recalc_task_prio(next, next->timestamp + delta);
  2621. if (unlikely(next->prio != new_prio)) {
  2622. dequeue_task(next, array);
  2623. next->prio = new_prio;
  2624. enqueue_task(next, array);
  2625. } else
  2626. requeue_task(next, array);
  2627. }
  2628. next->activated = 0;
  2629. switch_tasks:
  2630. if (next == rq->idle)
  2631. schedstat_inc(rq, sched_goidle);
  2632. prefetch(next);
  2633. prefetch_stack(next);
  2634. clear_tsk_need_resched(prev);
  2635. rcu_qsctr_inc(task_cpu(prev));
  2636. update_cpu_clock(prev, rq, now);
  2637. prev->sleep_avg -= run_time;
  2638. if ((long)prev->sleep_avg <= 0)
  2639. prev->sleep_avg = 0;
  2640. prev->timestamp = prev->last_ran = now;
  2641. sched_info_switch(prev, next);
  2642. if (likely(prev != next)) {
  2643. next->timestamp = now;
  2644. rq->nr_switches++;
  2645. rq->curr = next;
  2646. ++*switch_count;
  2647. prepare_task_switch(rq, next);
  2648. prev = context_switch(rq, prev, next);
  2649. barrier();
  2650. /*
  2651. * this_rq must be evaluated again because prev may have moved
  2652. * CPUs since it called schedule(), thus the 'rq' on its stack
  2653. * frame will be invalid.
  2654. */
  2655. finish_task_switch(this_rq(), prev);
  2656. } else
  2657. spin_unlock_irq(&rq->lock);
  2658. prev = current;
  2659. if (unlikely(reacquire_kernel_lock(prev) < 0))
  2660. goto need_resched_nonpreemptible;
  2661. preempt_enable_no_resched();
  2662. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2663. goto need_resched;
  2664. }
  2665. EXPORT_SYMBOL(schedule);
  2666. #ifdef CONFIG_PREEMPT
  2667. /*
  2668. * this is is the entry point to schedule() from in-kernel preemption
  2669. * off of preempt_enable. Kernel preemptions off return from interrupt
  2670. * occur there and call schedule directly.
  2671. */
  2672. asmlinkage void __sched preempt_schedule(void)
  2673. {
  2674. struct thread_info *ti = current_thread_info();
  2675. #ifdef CONFIG_PREEMPT_BKL
  2676. struct task_struct *task = current;
  2677. int saved_lock_depth;
  2678. #endif
  2679. /*
  2680. * If there is a non-zero preempt_count or interrupts are disabled,
  2681. * we do not want to preempt the current task. Just return..
  2682. */
  2683. if (unlikely(ti->preempt_count || irqs_disabled()))
  2684. return;
  2685. need_resched:
  2686. add_preempt_count(PREEMPT_ACTIVE);
  2687. /*
  2688. * We keep the big kernel semaphore locked, but we
  2689. * clear ->lock_depth so that schedule() doesnt
  2690. * auto-release the semaphore:
  2691. */
  2692. #ifdef CONFIG_PREEMPT_BKL
  2693. saved_lock_depth = task->lock_depth;
  2694. task->lock_depth = -1;
  2695. #endif
  2696. schedule();
  2697. #ifdef CONFIG_PREEMPT_BKL
  2698. task->lock_depth = saved_lock_depth;
  2699. #endif
  2700. sub_preempt_count(PREEMPT_ACTIVE);
  2701. /* we could miss a preemption opportunity between schedule and now */
  2702. barrier();
  2703. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2704. goto need_resched;
  2705. }
  2706. EXPORT_SYMBOL(preempt_schedule);
  2707. /*
  2708. * this is is the entry point to schedule() from kernel preemption
  2709. * off of irq context.
  2710. * Note, that this is called and return with irqs disabled. This will
  2711. * protect us against recursive calling from irq.
  2712. */
  2713. asmlinkage void __sched preempt_schedule_irq(void)
  2714. {
  2715. struct thread_info *ti = current_thread_info();
  2716. #ifdef CONFIG_PREEMPT_BKL
  2717. struct task_struct *task = current;
  2718. int saved_lock_depth;
  2719. #endif
  2720. /* Catch callers which need to be fixed*/
  2721. BUG_ON(ti->preempt_count || !irqs_disabled());
  2722. need_resched:
  2723. add_preempt_count(PREEMPT_ACTIVE);
  2724. /*
  2725. * We keep the big kernel semaphore locked, but we
  2726. * clear ->lock_depth so that schedule() doesnt
  2727. * auto-release the semaphore:
  2728. */
  2729. #ifdef CONFIG_PREEMPT_BKL
  2730. saved_lock_depth = task->lock_depth;
  2731. task->lock_depth = -1;
  2732. #endif
  2733. local_irq_enable();
  2734. schedule();
  2735. local_irq_disable();
  2736. #ifdef CONFIG_PREEMPT_BKL
  2737. task->lock_depth = saved_lock_depth;
  2738. #endif
  2739. sub_preempt_count(PREEMPT_ACTIVE);
  2740. /* we could miss a preemption opportunity between schedule and now */
  2741. barrier();
  2742. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2743. goto need_resched;
  2744. }
  2745. #endif /* CONFIG_PREEMPT */
  2746. int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
  2747. void *key)
  2748. {
  2749. task_t *p = curr->private;
  2750. return try_to_wake_up(p, mode, sync);
  2751. }
  2752. EXPORT_SYMBOL(default_wake_function);
  2753. /*
  2754. * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
  2755. * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
  2756. * number) then we wake all the non-exclusive tasks and one exclusive task.
  2757. *
  2758. * There are circumstances in which we can try to wake a task which has already
  2759. * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
  2760. * zero in this (rare) case, and we handle it by continuing to scan the queue.
  2761. */
  2762. static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
  2763. int nr_exclusive, int sync, void *key)
  2764. {
  2765. struct list_head *tmp, *next;
  2766. list_for_each_safe(tmp, next, &q->task_list) {
  2767. wait_queue_t *curr;
  2768. unsigned flags;
  2769. curr = list_entry(tmp, wait_queue_t, task_list);
  2770. flags = curr->flags;
  2771. if (curr->func(curr, mode, sync, key) &&
  2772. (flags & WQ_FLAG_EXCLUSIVE) &&
  2773. !--nr_exclusive)
  2774. break;
  2775. }
  2776. }
  2777. /**
  2778. * __wake_up - wake up threads blocked on a waitqueue.
  2779. * @q: the waitqueue
  2780. * @mode: which threads
  2781. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  2782. * @key: is directly passed to the wakeup function
  2783. */
  2784. void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
  2785. int nr_exclusive, void *key)
  2786. {
  2787. unsigned long flags;
  2788. spin_lock_irqsave(&q->lock, flags);
  2789. __wake_up_common(q, mode, nr_exclusive, 0, key);
  2790. spin_unlock_irqrestore(&q->lock, flags);
  2791. }
  2792. EXPORT_SYMBOL(__wake_up);
  2793. /*
  2794. * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
  2795. */
  2796. void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
  2797. {
  2798. __wake_up_common(q, mode, 1, 0, NULL);
  2799. }
  2800. /**
  2801. * __wake_up_sync - wake up threads blocked on a waitqueue.
  2802. * @q: the waitqueue
  2803. * @mode: which threads
  2804. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  2805. *
  2806. * The sync wakeup differs that the waker knows that it will schedule
  2807. * away soon, so while the target thread will be woken up, it will not
  2808. * be migrated to another CPU - ie. the two threads are 'synchronized'
  2809. * with each other. This can prevent needless bouncing between CPUs.
  2810. *
  2811. * On UP it can prevent extra preemption.
  2812. */
  2813. void fastcall
  2814. __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
  2815. {
  2816. unsigned long flags;
  2817. int sync = 1;
  2818. if (unlikely(!q))
  2819. return;
  2820. if (unlikely(!nr_exclusive))
  2821. sync = 0;
  2822. spin_lock_irqsave(&q->lock, flags);
  2823. __wake_up_common(q, mode, nr_exclusive, sync, NULL);
  2824. spin_unlock_irqrestore(&q->lock, flags);
  2825. }
  2826. EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
  2827. void fastcall complete(struct completion *x)
  2828. {
  2829. unsigned long flags;
  2830. spin_lock_irqsave(&x->wait.lock, flags);
  2831. x->done++;
  2832. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  2833. 1, 0, NULL);
  2834. spin_unlock_irqrestore(&x->wait.lock, flags);
  2835. }
  2836. EXPORT_SYMBOL(complete);
  2837. void fastcall complete_all(struct completion *x)
  2838. {
  2839. unsigned long flags;
  2840. spin_lock_irqsave(&x->wait.lock, flags);
  2841. x->done += UINT_MAX/2;
  2842. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  2843. 0, 0, NULL);
  2844. spin_unlock_irqrestore(&x->wait.lock, flags);
  2845. }
  2846. EXPORT_SYMBOL(complete_all);
  2847. void fastcall __sched wait_for_completion(struct completion *x)
  2848. {
  2849. might_sleep();
  2850. spin_lock_irq(&x->wait.lock);
  2851. if (!x->done) {
  2852. DECLARE_WAITQUEUE(wait, current);
  2853. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2854. __add_wait_queue_tail(&x->wait, &wait);
  2855. do {
  2856. __set_current_state(TASK_UNINTERRUPTIBLE);
  2857. spin_unlock_irq(&x->wait.lock);
  2858. schedule();
  2859. spin_lock_irq(&x->wait.lock);
  2860. } while (!x->done);
  2861. __remove_wait_queue(&x->wait, &wait);
  2862. }
  2863. x->done--;
  2864. spin_unlock_irq(&x->wait.lock);
  2865. }
  2866. EXPORT_SYMBOL(wait_for_completion);
  2867. unsigned long fastcall __sched
  2868. wait_for_completion_timeout(struct completion *x, unsigned long timeout)
  2869. {
  2870. might_sleep();
  2871. spin_lock_irq(&x->wait.lock);
  2872. if (!x->done) {
  2873. DECLARE_WAITQUEUE(wait, current);
  2874. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2875. __add_wait_queue_tail(&x->wait, &wait);
  2876. do {
  2877. __set_current_state(TASK_UNINTERRUPTIBLE);
  2878. spin_unlock_irq(&x->wait.lock);
  2879. timeout = schedule_timeout(timeout);
  2880. spin_lock_irq(&x->wait.lock);
  2881. if (!timeout) {
  2882. __remove_wait_queue(&x->wait, &wait);
  2883. goto out;
  2884. }
  2885. } while (!x->done);
  2886. __remove_wait_queue(&x->wait, &wait);
  2887. }
  2888. x->done--;
  2889. out:
  2890. spin_unlock_irq(&x->wait.lock);
  2891. return timeout;
  2892. }
  2893. EXPORT_SYMBOL(wait_for_completion_timeout);
  2894. int fastcall __sched wait_for_completion_interruptible(struct completion *x)
  2895. {
  2896. int ret = 0;
  2897. might_sleep();
  2898. spin_lock_irq(&x->wait.lock);
  2899. if (!x->done) {
  2900. DECLARE_WAITQUEUE(wait, current);
  2901. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2902. __add_wait_queue_tail(&x->wait, &wait);
  2903. do {
  2904. if (signal_pending(current)) {
  2905. ret = -ERESTARTSYS;
  2906. __remove_wait_queue(&x->wait, &wait);
  2907. goto out;
  2908. }
  2909. __set_current_state(TASK_INTERRUPTIBLE);
  2910. spin_unlock_irq(&x->wait.lock);
  2911. schedule();
  2912. spin_lock_irq(&x->wait.lock);
  2913. } while (!x->done);
  2914. __remove_wait_queue(&x->wait, &wait);
  2915. }
  2916. x->done--;
  2917. out:
  2918. spin_unlock_irq(&x->wait.lock);
  2919. return ret;
  2920. }
  2921. EXPORT_SYMBOL(wait_for_completion_interruptible);
  2922. unsigned long fastcall __sched
  2923. wait_for_completion_interruptible_timeout(struct completion *x,
  2924. unsigned long timeout)
  2925. {
  2926. might_sleep();
  2927. spin_lock_irq(&x->wait.lock);
  2928. if (!x->done) {
  2929. DECLARE_WAITQUEUE(wait, current);
  2930. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2931. __add_wait_queue_tail(&x->wait, &wait);
  2932. do {
  2933. if (signal_pending(current)) {
  2934. timeout = -ERESTARTSYS;
  2935. __remove_wait_queue(&x->wait, &wait);
  2936. goto out;
  2937. }
  2938. __set_current_state(TASK_INTERRUPTIBLE);
  2939. spin_unlock_irq(&x->wait.lock);
  2940. timeout = schedule_timeout(timeout);
  2941. spin_lock_irq(&x->wait.lock);
  2942. if (!timeout) {
  2943. __remove_wait_queue(&x->wait, &wait);
  2944. goto out;
  2945. }
  2946. } while (!x->done);
  2947. __remove_wait_queue(&x->wait, &wait);
  2948. }
  2949. x->done--;
  2950. out:
  2951. spin_unlock_irq(&x->wait.lock);
  2952. return timeout;
  2953. }
  2954. EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
  2955. #define SLEEP_ON_VAR \
  2956. unsigned long flags; \
  2957. wait_queue_t wait; \
  2958. init_waitqueue_entry(&wait, current);
  2959. #define SLEEP_ON_HEAD \
  2960. spin_lock_irqsave(&q->lock,flags); \
  2961. __add_wait_queue(q, &wait); \
  2962. spin_unlock(&q->lock);
  2963. #define SLEEP_ON_TAIL \
  2964. spin_lock_irq(&q->lock); \
  2965. __remove_wait_queue(q, &wait); \
  2966. spin_unlock_irqrestore(&q->lock, flags);
  2967. void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
  2968. {
  2969. SLEEP_ON_VAR
  2970. current->state = TASK_INTERRUPTIBLE;
  2971. SLEEP_ON_HEAD
  2972. schedule();
  2973. SLEEP_ON_TAIL
  2974. }
  2975. EXPORT_SYMBOL(interruptible_sleep_on);
  2976. long fastcall __sched
  2977. interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
  2978. {
  2979. SLEEP_ON_VAR
  2980. current->state = TASK_INTERRUPTIBLE;
  2981. SLEEP_ON_HEAD
  2982. timeout = schedule_timeout(timeout);
  2983. SLEEP_ON_TAIL
  2984. return timeout;
  2985. }
  2986. EXPORT_SYMBOL(interruptible_sleep_on_timeout);
  2987. void fastcall __sched sleep_on(wait_queue_head_t *q)
  2988. {
  2989. SLEEP_ON_VAR
  2990. current->state = TASK_UNINTERRUPTIBLE;
  2991. SLEEP_ON_HEAD
  2992. schedule();
  2993. SLEEP_ON_TAIL
  2994. }
  2995. EXPORT_SYMBOL(sleep_on);
  2996. long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
  2997. {
  2998. SLEEP_ON_VAR
  2999. current->state = TASK_UNINTERRUPTIBLE;
  3000. SLEEP_ON_HEAD
  3001. timeout = schedule_timeout(timeout);
  3002. SLEEP_ON_TAIL
  3003. return timeout;
  3004. }
  3005. EXPORT_SYMBOL(sleep_on_timeout);
  3006. void set_user_nice(task_t *p, long nice)
  3007. {
  3008. unsigned long flags;
  3009. prio_array_t *array;
  3010. runqueue_t *rq;
  3011. int old_prio, new_prio, delta;
  3012. if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
  3013. return;
  3014. /*
  3015. * We have to be careful, if called from sys_setpriority(),
  3016. * the task might be in the middle of scheduling on another CPU.
  3017. */
  3018. rq = task_rq_lock(p, &flags);
  3019. /*
  3020. * The RT priorities are set via sched_setscheduler(), but we still
  3021. * allow the 'normal' nice value to be set - but as expected
  3022. * it wont have any effect on scheduling until the task is
  3023. * not SCHED_NORMAL/SCHED_BATCH:
  3024. */
  3025. if (rt_task(p)) {
  3026. p->static_prio = NICE_TO_PRIO(nice);
  3027. goto out_unlock;
  3028. }
  3029. array = p->array;
  3030. if (array)
  3031. dequeue_task(p, array);
  3032. old_prio = p->prio;
  3033. new_prio = NICE_TO_PRIO(nice);
  3034. delta = new_prio - old_prio;
  3035. p->static_prio = NICE_TO_PRIO(nice);
  3036. p->prio += delta;
  3037. if (array) {
  3038. enqueue_task(p, array);
  3039. /*
  3040. * If the task increased its priority or is running and
  3041. * lowered its priority, then reschedule its CPU:
  3042. */
  3043. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  3044. resched_task(rq->curr);
  3045. }
  3046. out_unlock:
  3047. task_rq_unlock(rq, &flags);
  3048. }
  3049. EXPORT_SYMBOL(set_user_nice);
  3050. /*
  3051. * can_nice - check if a task can reduce its nice value
  3052. * @p: task
  3053. * @nice: nice value
  3054. */
  3055. int can_nice(const task_t *p, const int nice)
  3056. {
  3057. /* convert nice value [19,-20] to rlimit style value [1,40] */
  3058. int nice_rlim = 20 - nice;
  3059. return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
  3060. capable(CAP_SYS_NICE));
  3061. }
  3062. #ifdef __ARCH_WANT_SYS_NICE
  3063. /*
  3064. * sys_nice - change the priority of the current process.
  3065. * @increment: priority increment
  3066. *
  3067. * sys_setpriority is a more generic, but much slower function that
  3068. * does similar things.
  3069. */
  3070. asmlinkage long sys_nice(int increment)
  3071. {
  3072. int retval;
  3073. long nice;
  3074. /*
  3075. * Setpriority might change our priority at the same moment.
  3076. * We don't have to worry. Conceptually one call occurs first
  3077. * and we have a single winner.
  3078. */
  3079. if (increment < -40)
  3080. increment = -40;
  3081. if (increment > 40)
  3082. increment = 40;
  3083. nice = PRIO_TO_NICE(current->static_prio) + increment;
  3084. if (nice < -20)
  3085. nice = -20;
  3086. if (nice > 19)
  3087. nice = 19;
  3088. if (increment < 0 && !can_nice(current, nice))
  3089. return -EPERM;
  3090. retval = security_task_setnice(current, nice);
  3091. if (retval)
  3092. return retval;
  3093. set_user_nice(current, nice);
  3094. return 0;
  3095. }
  3096. #endif
  3097. /**
  3098. * task_prio - return the priority value of a given task.
  3099. * @p: the task in question.
  3100. *
  3101. * This is the priority value as seen by users in /proc.
  3102. * RT tasks are offset by -200. Normal tasks are centered
  3103. * around 0, value goes from -16 to +15.
  3104. */
  3105. int task_prio(const task_t *p)
  3106. {
  3107. return p->prio - MAX_RT_PRIO;
  3108. }
  3109. /**
  3110. * task_nice - return the nice value of a given task.
  3111. * @p: the task in question.
  3112. */
  3113. int task_nice(const task_t *p)
  3114. {
  3115. return TASK_NICE(p);
  3116. }
  3117. EXPORT_SYMBOL_GPL(task_nice);
  3118. /**
  3119. * idle_cpu - is a given cpu idle currently?
  3120. * @cpu: the processor in question.
  3121. */
  3122. int idle_cpu(int cpu)
  3123. {
  3124. return cpu_curr(cpu) == cpu_rq(cpu)->idle;
  3125. }
  3126. /**
  3127. * idle_task - return the idle task for a given cpu.
  3128. * @cpu: the processor in question.
  3129. */
  3130. task_t *idle_task(int cpu)
  3131. {
  3132. return cpu_rq(cpu)->idle;
  3133. }
  3134. /**
  3135. * find_process_by_pid - find a process with a matching PID value.
  3136. * @pid: the pid in question.
  3137. */
  3138. static inline task_t *find_process_by_pid(pid_t pid)
  3139. {
  3140. return pid ? find_task_by_pid(pid) : current;
  3141. }
  3142. /* Actually do priority change: must hold rq lock. */
  3143. static void __setscheduler(struct task_struct *p, int policy, int prio)
  3144. {
  3145. BUG_ON(p->array);
  3146. p->policy = policy;
  3147. p->rt_priority = prio;
  3148. if (policy != SCHED_NORMAL && policy != SCHED_BATCH) {
  3149. p->prio = MAX_RT_PRIO-1 - p->rt_priority;
  3150. } else {
  3151. p->prio = p->static_prio;
  3152. /*
  3153. * SCHED_BATCH tasks are treated as perpetual CPU hogs:
  3154. */
  3155. if (policy == SCHED_BATCH)
  3156. p->sleep_avg = 0;
  3157. }
  3158. }
  3159. /**
  3160. * sched_setscheduler - change the scheduling policy and/or RT priority of
  3161. * a thread.
  3162. * @p: the task in question.
  3163. * @policy: new policy.
  3164. * @param: structure containing the new RT priority.
  3165. */
  3166. int sched_setscheduler(struct task_struct *p, int policy,
  3167. struct sched_param *param)
  3168. {
  3169. int retval;
  3170. int oldprio, oldpolicy = -1;
  3171. prio_array_t *array;
  3172. unsigned long flags;
  3173. runqueue_t *rq;
  3174. recheck:
  3175. /* double check policy once rq lock held */
  3176. if (policy < 0)
  3177. policy = oldpolicy = p->policy;
  3178. else if (policy != SCHED_FIFO && policy != SCHED_RR &&
  3179. policy != SCHED_NORMAL && policy != SCHED_BATCH)
  3180. return -EINVAL;
  3181. /*
  3182. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3183. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
  3184. * SCHED_BATCH is 0.
  3185. */
  3186. if (param->sched_priority < 0 ||
  3187. (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
  3188. (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
  3189. return -EINVAL;
  3190. if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
  3191. != (param->sched_priority == 0))
  3192. return -EINVAL;
  3193. /*
  3194. * Allow unprivileged RT tasks to decrease priority:
  3195. */
  3196. if (!capable(CAP_SYS_NICE)) {
  3197. /*
  3198. * can't change policy, except between SCHED_NORMAL
  3199. * and SCHED_BATCH:
  3200. */
  3201. if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
  3202. (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
  3203. !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
  3204. return -EPERM;
  3205. /* can't increase priority */
  3206. if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
  3207. param->sched_priority > p->rt_priority &&
  3208. param->sched_priority >
  3209. p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
  3210. return -EPERM;
  3211. /* can't change other user's priorities */
  3212. if ((current->euid != p->euid) &&
  3213. (current->euid != p->uid))
  3214. return -EPERM;
  3215. }
  3216. retval = security_task_setscheduler(p, policy, param);
  3217. if (retval)
  3218. return retval;
  3219. /*
  3220. * To be able to change p->policy safely, the apropriate
  3221. * runqueue lock must be held.
  3222. */
  3223. rq = task_rq_lock(p, &flags);
  3224. /* recheck policy now with rq lock held */
  3225. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3226. policy = oldpolicy = -1;
  3227. task_rq_unlock(rq, &flags);
  3228. goto recheck;
  3229. }
  3230. array = p->array;
  3231. if (array)
  3232. deactivate_task(p, rq);
  3233. oldprio = p->prio;
  3234. __setscheduler(p, policy, param->sched_priority);
  3235. if (array) {
  3236. __activate_task(p, rq);
  3237. /*
  3238. * Reschedule if we are currently running on this runqueue and
  3239. * our priority decreased, or if we are not currently running on
  3240. * this runqueue and our priority is higher than the current's
  3241. */
  3242. if (task_running(rq, p)) {
  3243. if (p->prio > oldprio)
  3244. resched_task(rq->curr);
  3245. } else if (TASK_PREEMPTS_CURR(p, rq))
  3246. resched_task(rq->curr);
  3247. }
  3248. task_rq_unlock(rq, &flags);
  3249. return 0;
  3250. }
  3251. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3252. static int
  3253. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3254. {
  3255. int retval;
  3256. struct sched_param lparam;
  3257. struct task_struct *p;
  3258. if (!param || pid < 0)
  3259. return -EINVAL;
  3260. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3261. return -EFAULT;
  3262. read_lock_irq(&tasklist_lock);
  3263. p = find_process_by_pid(pid);
  3264. if (!p) {
  3265. read_unlock_irq(&tasklist_lock);
  3266. return -ESRCH;
  3267. }
  3268. retval = sched_setscheduler(p, policy, &lparam);
  3269. read_unlock_irq(&tasklist_lock);
  3270. return retval;
  3271. }
  3272. /**
  3273. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3274. * @pid: the pid in question.
  3275. * @policy: new policy.
  3276. * @param: structure containing the new RT priority.
  3277. */
  3278. asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
  3279. struct sched_param __user *param)
  3280. {
  3281. /* negative values for policy are not valid */
  3282. if (policy < 0)
  3283. return -EINVAL;
  3284. return do_sched_setscheduler(pid, policy, param);
  3285. }
  3286. /**
  3287. * sys_sched_setparam - set/change the RT priority of a thread
  3288. * @pid: the pid in question.
  3289. * @param: structure containing the new RT priority.
  3290. */
  3291. asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
  3292. {
  3293. return do_sched_setscheduler(pid, -1, param);
  3294. }
  3295. /**
  3296. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3297. * @pid: the pid in question.
  3298. */
  3299. asmlinkage long sys_sched_getscheduler(pid_t pid)
  3300. {
  3301. int retval = -EINVAL;
  3302. task_t *p;
  3303. if (pid < 0)
  3304. goto out_nounlock;
  3305. retval = -ESRCH;
  3306. read_lock(&tasklist_lock);
  3307. p = find_process_by_pid(pid);
  3308. if (p) {
  3309. retval = security_task_getscheduler(p);
  3310. if (!retval)
  3311. retval = p->policy;
  3312. }
  3313. read_unlock(&tasklist_lock);
  3314. out_nounlock:
  3315. return retval;
  3316. }
  3317. /**
  3318. * sys_sched_getscheduler - get the RT priority of a thread
  3319. * @pid: the pid in question.
  3320. * @param: structure containing the RT priority.
  3321. */
  3322. asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
  3323. {
  3324. struct sched_param lp;
  3325. int retval = -EINVAL;
  3326. task_t *p;
  3327. if (!param || pid < 0)
  3328. goto out_nounlock;
  3329. read_lock(&tasklist_lock);
  3330. p = find_process_by_pid(pid);
  3331. retval = -ESRCH;
  3332. if (!p)
  3333. goto out_unlock;
  3334. retval = security_task_getscheduler(p);
  3335. if (retval)
  3336. goto out_unlock;
  3337. lp.sched_priority = p->rt_priority;
  3338. read_unlock(&tasklist_lock);
  3339. /*
  3340. * This one might sleep, we cannot do it with a spinlock held ...
  3341. */
  3342. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  3343. out_nounlock:
  3344. return retval;
  3345. out_unlock:
  3346. read_unlock(&tasklist_lock);
  3347. return retval;
  3348. }
  3349. long sched_setaffinity(pid_t pid, cpumask_t new_mask)
  3350. {
  3351. task_t *p;
  3352. int retval;
  3353. cpumask_t cpus_allowed;
  3354. lock_cpu_hotplug();
  3355. read_lock(&tasklist_lock);
  3356. p = find_process_by_pid(pid);
  3357. if (!p) {
  3358. read_unlock(&tasklist_lock);
  3359. unlock_cpu_hotplug();
  3360. return -ESRCH;
  3361. }
  3362. /*
  3363. * It is not safe to call set_cpus_allowed with the
  3364. * tasklist_lock held. We will bump the task_struct's
  3365. * usage count and then drop tasklist_lock.
  3366. */
  3367. get_task_struct(p);
  3368. read_unlock(&tasklist_lock);
  3369. retval = -EPERM;
  3370. if ((current->euid != p->euid) && (current->euid != p->uid) &&
  3371. !capable(CAP_SYS_NICE))
  3372. goto out_unlock;
  3373. cpus_allowed = cpuset_cpus_allowed(p);
  3374. cpus_and(new_mask, new_mask, cpus_allowed);
  3375. retval = set_cpus_allowed(p, new_mask);
  3376. out_unlock:
  3377. put_task_struct(p);
  3378. unlock_cpu_hotplug();
  3379. return retval;
  3380. }
  3381. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  3382. cpumask_t *new_mask)
  3383. {
  3384. if (len < sizeof(cpumask_t)) {
  3385. memset(new_mask, 0, sizeof(cpumask_t));
  3386. } else if (len > sizeof(cpumask_t)) {
  3387. len = sizeof(cpumask_t);
  3388. }
  3389. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  3390. }
  3391. /**
  3392. * sys_sched_setaffinity - set the cpu affinity of a process
  3393. * @pid: pid of the process
  3394. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3395. * @user_mask_ptr: user-space pointer to the new cpu mask
  3396. */
  3397. asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
  3398. unsigned long __user *user_mask_ptr)
  3399. {
  3400. cpumask_t new_mask;
  3401. int retval;
  3402. retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
  3403. if (retval)
  3404. return retval;
  3405. return sched_setaffinity(pid, new_mask);
  3406. }
  3407. /*
  3408. * Represents all cpu's present in the system
  3409. * In systems capable of hotplug, this map could dynamically grow
  3410. * as new cpu's are detected in the system via any platform specific
  3411. * method, such as ACPI for e.g.
  3412. */
  3413. cpumask_t cpu_present_map __read_mostly;
  3414. EXPORT_SYMBOL(cpu_present_map);
  3415. #ifndef CONFIG_SMP
  3416. cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
  3417. cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
  3418. #endif
  3419. long sched_getaffinity(pid_t pid, cpumask_t *mask)
  3420. {
  3421. int retval;
  3422. task_t *p;
  3423. lock_cpu_hotplug();
  3424. read_lock(&tasklist_lock);
  3425. retval = -ESRCH;
  3426. p = find_process_by_pid(pid);
  3427. if (!p)
  3428. goto out_unlock;
  3429. retval = 0;
  3430. cpus_and(*mask, p->cpus_allowed, cpu_online_map);
  3431. out_unlock:
  3432. read_unlock(&tasklist_lock);
  3433. unlock_cpu_hotplug();
  3434. if (retval)
  3435. return retval;
  3436. return 0;
  3437. }
  3438. /**
  3439. * sys_sched_getaffinity - get the cpu affinity of a process
  3440. * @pid: pid of the process
  3441. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3442. * @user_mask_ptr: user-space pointer to hold the current cpu mask
  3443. */
  3444. asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
  3445. unsigned long __user *user_mask_ptr)
  3446. {
  3447. int ret;
  3448. cpumask_t mask;
  3449. if (len < sizeof(cpumask_t))
  3450. return -EINVAL;
  3451. ret = sched_getaffinity(pid, &mask);
  3452. if (ret < 0)
  3453. return ret;
  3454. if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
  3455. return -EFAULT;
  3456. return sizeof(cpumask_t);
  3457. }
  3458. /**
  3459. * sys_sched_yield - yield the current processor to other threads.
  3460. *
  3461. * this function yields the current CPU by moving the calling thread
  3462. * to the expired array. If there are no other threads running on this
  3463. * CPU then this function will return.
  3464. */
  3465. asmlinkage long sys_sched_yield(void)
  3466. {
  3467. runqueue_t *rq = this_rq_lock();
  3468. prio_array_t *array = current->array;
  3469. prio_array_t *target = rq->expired;
  3470. schedstat_inc(rq, yld_cnt);
  3471. /*
  3472. * We implement yielding by moving the task into the expired
  3473. * queue.
  3474. *
  3475. * (special rule: RT tasks will just roundrobin in the active
  3476. * array.)
  3477. */
  3478. if (rt_task(current))
  3479. target = rq->active;
  3480. if (array->nr_active == 1) {
  3481. schedstat_inc(rq, yld_act_empty);
  3482. if (!rq->expired->nr_active)
  3483. schedstat_inc(rq, yld_both_empty);
  3484. } else if (!rq->expired->nr_active)
  3485. schedstat_inc(rq, yld_exp_empty);
  3486. if (array != target) {
  3487. dequeue_task(current, array);
  3488. enqueue_task(current, target);
  3489. } else
  3490. /*
  3491. * requeue_task is cheaper so perform that if possible.
  3492. */
  3493. requeue_task(current, array);
  3494. /*
  3495. * Since we are going to call schedule() anyway, there's
  3496. * no need to preempt or enable interrupts:
  3497. */
  3498. __release(rq->lock);
  3499. _raw_spin_unlock(&rq->lock);
  3500. preempt_enable_no_resched();
  3501. schedule();
  3502. return 0;
  3503. }
  3504. static inline void __cond_resched(void)
  3505. {
  3506. /*
  3507. * The BKS might be reacquired before we have dropped
  3508. * PREEMPT_ACTIVE, which could trigger a second
  3509. * cond_resched() call.
  3510. */
  3511. if (unlikely(preempt_count()))
  3512. return;
  3513. do {
  3514. add_preempt_count(PREEMPT_ACTIVE);
  3515. schedule();
  3516. sub_preempt_count(PREEMPT_ACTIVE);
  3517. } while (need_resched());
  3518. }
  3519. int __sched cond_resched(void)
  3520. {
  3521. if (need_resched()) {
  3522. __cond_resched();
  3523. return 1;
  3524. }
  3525. return 0;
  3526. }
  3527. EXPORT_SYMBOL(cond_resched);
  3528. /*
  3529. * cond_resched_lock() - if a reschedule is pending, drop the given lock,
  3530. * call schedule, and on return reacquire the lock.
  3531. *
  3532. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  3533. * operations here to prevent schedule() from being called twice (once via
  3534. * spin_unlock(), once by hand).
  3535. */
  3536. int cond_resched_lock(spinlock_t *lock)
  3537. {
  3538. int ret = 0;
  3539. if (need_lockbreak(lock)) {
  3540. spin_unlock(lock);
  3541. cpu_relax();
  3542. ret = 1;
  3543. spin_lock(lock);
  3544. }
  3545. if (need_resched()) {
  3546. _raw_spin_unlock(lock);
  3547. preempt_enable_no_resched();
  3548. __cond_resched();
  3549. ret = 1;
  3550. spin_lock(lock);
  3551. }
  3552. return ret;
  3553. }
  3554. EXPORT_SYMBOL(cond_resched_lock);
  3555. int __sched cond_resched_softirq(void)
  3556. {
  3557. BUG_ON(!in_softirq());
  3558. if (need_resched()) {
  3559. __local_bh_enable();
  3560. __cond_resched();
  3561. local_bh_disable();
  3562. return 1;
  3563. }
  3564. return 0;
  3565. }
  3566. EXPORT_SYMBOL(cond_resched_softirq);
  3567. /**
  3568. * yield - yield the current processor to other threads.
  3569. *
  3570. * this is a shortcut for kernel-space yielding - it marks the
  3571. * thread runnable and calls sys_sched_yield().
  3572. */
  3573. void __sched yield(void)
  3574. {
  3575. set_current_state(TASK_RUNNING);
  3576. sys_sched_yield();
  3577. }
  3578. EXPORT_SYMBOL(yield);
  3579. /*
  3580. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  3581. * that process accounting knows that this is a task in IO wait state.
  3582. *
  3583. * But don't do that if it is a deliberate, throttling IO wait (this task
  3584. * has set its backing_dev_info: the queue against which it should throttle)
  3585. */
  3586. void __sched io_schedule(void)
  3587. {
  3588. struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
  3589. atomic_inc(&rq->nr_iowait);
  3590. schedule();
  3591. atomic_dec(&rq->nr_iowait);
  3592. }
  3593. EXPORT_SYMBOL(io_schedule);
  3594. long __sched io_schedule_timeout(long timeout)
  3595. {
  3596. struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
  3597. long ret;
  3598. atomic_inc(&rq->nr_iowait);
  3599. ret = schedule_timeout(timeout);
  3600. atomic_dec(&rq->nr_iowait);
  3601. return ret;
  3602. }
  3603. /**
  3604. * sys_sched_get_priority_max - return maximum RT priority.
  3605. * @policy: scheduling class.
  3606. *
  3607. * this syscall returns the maximum rt_priority that can be used
  3608. * by a given scheduling class.
  3609. */
  3610. asmlinkage long sys_sched_get_priority_max(int policy)
  3611. {
  3612. int ret = -EINVAL;
  3613. switch (policy) {
  3614. case SCHED_FIFO:
  3615. case SCHED_RR:
  3616. ret = MAX_USER_RT_PRIO-1;
  3617. break;
  3618. case SCHED_NORMAL:
  3619. case SCHED_BATCH:
  3620. ret = 0;
  3621. break;
  3622. }
  3623. return ret;
  3624. }
  3625. /**
  3626. * sys_sched_get_priority_min - return minimum RT priority.
  3627. * @policy: scheduling class.
  3628. *
  3629. * this syscall returns the minimum rt_priority that can be used
  3630. * by a given scheduling class.
  3631. */
  3632. asmlinkage long sys_sched_get_priority_min(int policy)
  3633. {
  3634. int ret = -EINVAL;
  3635. switch (policy) {
  3636. case SCHED_FIFO:
  3637. case SCHED_RR:
  3638. ret = 1;
  3639. break;
  3640. case SCHED_NORMAL:
  3641. case SCHED_BATCH:
  3642. ret = 0;
  3643. }
  3644. return ret;
  3645. }
  3646. /**
  3647. * sys_sched_rr_get_interval - return the default timeslice of a process.
  3648. * @pid: pid of the process.
  3649. * @interval: userspace pointer to the timeslice value.
  3650. *
  3651. * this syscall writes the default timeslice value of a given process
  3652. * into the user-space timespec buffer. A value of '0' means infinity.
  3653. */
  3654. asmlinkage
  3655. long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
  3656. {
  3657. int retval = -EINVAL;
  3658. struct timespec t;
  3659. task_t *p;
  3660. if (pid < 0)
  3661. goto out_nounlock;
  3662. retval = -ESRCH;
  3663. read_lock(&tasklist_lock);
  3664. p = find_process_by_pid(pid);
  3665. if (!p)
  3666. goto out_unlock;
  3667. retval = security_task_getscheduler(p);
  3668. if (retval)
  3669. goto out_unlock;
  3670. jiffies_to_timespec(p->policy & SCHED_FIFO ?
  3671. 0 : task_timeslice(p), &t);
  3672. read_unlock(&tasklist_lock);
  3673. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  3674. out_nounlock:
  3675. return retval;
  3676. out_unlock:
  3677. read_unlock(&tasklist_lock);
  3678. return retval;
  3679. }
  3680. static inline struct task_struct *eldest_child(struct task_struct *p)
  3681. {
  3682. if (list_empty(&p->children)) return NULL;
  3683. return list_entry(p->children.next,struct task_struct,sibling);
  3684. }
  3685. static inline struct task_struct *older_sibling(struct task_struct *p)
  3686. {
  3687. if (p->sibling.prev==&p->parent->children) return NULL;
  3688. return list_entry(p->sibling.prev,struct task_struct,sibling);
  3689. }
  3690. static inline struct task_struct *younger_sibling(struct task_struct *p)
  3691. {
  3692. if (p->sibling.next==&p->parent->children) return NULL;
  3693. return list_entry(p->sibling.next,struct task_struct,sibling);
  3694. }
  3695. static void show_task(task_t *p)
  3696. {
  3697. task_t *relative;
  3698. unsigned state;
  3699. unsigned long free = 0;
  3700. static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
  3701. printk("%-13.13s ", p->comm);
  3702. state = p->state ? __ffs(p->state) + 1 : 0;
  3703. if (state < ARRAY_SIZE(stat_nam))
  3704. printk(stat_nam[state]);
  3705. else
  3706. printk("?");
  3707. #if (BITS_PER_LONG == 32)
  3708. if (state == TASK_RUNNING)
  3709. printk(" running ");
  3710. else
  3711. printk(" %08lX ", thread_saved_pc(p));
  3712. #else
  3713. if (state == TASK_RUNNING)
  3714. printk(" running task ");
  3715. else
  3716. printk(" %016lx ", thread_saved_pc(p));
  3717. #endif
  3718. #ifdef CONFIG_DEBUG_STACK_USAGE
  3719. {
  3720. unsigned long *n = end_of_stack(p);
  3721. while (!*n)
  3722. n++;
  3723. free = (unsigned long)n - (unsigned long)end_of_stack(p);
  3724. }
  3725. #endif
  3726. printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
  3727. if ((relative = eldest_child(p)))
  3728. printk("%5d ", relative->pid);
  3729. else
  3730. printk(" ");
  3731. if ((relative = younger_sibling(p)))
  3732. printk("%7d", relative->pid);
  3733. else
  3734. printk(" ");
  3735. if ((relative = older_sibling(p)))
  3736. printk(" %5d", relative->pid);
  3737. else
  3738. printk(" ");
  3739. if (!p->mm)
  3740. printk(" (L-TLB)\n");
  3741. else
  3742. printk(" (NOTLB)\n");
  3743. if (state != TASK_RUNNING)
  3744. show_stack(p, NULL);
  3745. }
  3746. void show_state(void)
  3747. {
  3748. task_t *g, *p;
  3749. #if (BITS_PER_LONG == 32)
  3750. printk("\n"
  3751. " sibling\n");
  3752. printk(" task PC pid father child younger older\n");
  3753. #else
  3754. printk("\n"
  3755. " sibling\n");
  3756. printk(" task PC pid father child younger older\n");
  3757. #endif
  3758. read_lock(&tasklist_lock);
  3759. do_each_thread(g, p) {
  3760. /*
  3761. * reset the NMI-timeout, listing all files on a slow
  3762. * console might take alot of time:
  3763. */
  3764. touch_nmi_watchdog();
  3765. show_task(p);
  3766. } while_each_thread(g, p);
  3767. read_unlock(&tasklist_lock);
  3768. mutex_debug_show_all_locks();
  3769. }
  3770. /**
  3771. * init_idle - set up an idle thread for a given CPU
  3772. * @idle: task in question
  3773. * @cpu: cpu the idle task belongs to
  3774. *
  3775. * NOTE: this function does not set the idle thread's NEED_RESCHED
  3776. * flag, to make booting more robust.
  3777. */
  3778. void __devinit init_idle(task_t *idle, int cpu)
  3779. {
  3780. runqueue_t *rq = cpu_rq(cpu);
  3781. unsigned long flags;
  3782. idle->sleep_avg = 0;
  3783. idle->array = NULL;
  3784. idle->prio = MAX_PRIO;
  3785. idle->state = TASK_RUNNING;
  3786. idle->cpus_allowed = cpumask_of_cpu(cpu);
  3787. set_task_cpu(idle, cpu);
  3788. spin_lock_irqsave(&rq->lock, flags);
  3789. rq->curr = rq->idle = idle;
  3790. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  3791. idle->oncpu = 1;
  3792. #endif
  3793. spin_unlock_irqrestore(&rq->lock, flags);
  3794. /* Set the preempt count _outside_ the spinlocks! */
  3795. #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
  3796. task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
  3797. #else
  3798. task_thread_info(idle)->preempt_count = 0;
  3799. #endif
  3800. }
  3801. /*
  3802. * In a system that switches off the HZ timer nohz_cpu_mask
  3803. * indicates which cpus entered this state. This is used
  3804. * in the rcu update to wait only for active cpus. For system
  3805. * which do not switch off the HZ timer nohz_cpu_mask should
  3806. * always be CPU_MASK_NONE.
  3807. */
  3808. cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
  3809. #ifdef CONFIG_SMP
  3810. /*
  3811. * This is how migration works:
  3812. *
  3813. * 1) we queue a migration_req_t structure in the source CPU's
  3814. * runqueue and wake up that CPU's migration thread.
  3815. * 2) we down() the locked semaphore => thread blocks.
  3816. * 3) migration thread wakes up (implicitly it forces the migrated
  3817. * thread off the CPU)
  3818. * 4) it gets the migration request and checks whether the migrated
  3819. * task is still in the wrong runqueue.
  3820. * 5) if it's in the wrong runqueue then the migration thread removes
  3821. * it and puts it into the right queue.
  3822. * 6) migration thread up()s the semaphore.
  3823. * 7) we wake up and the migration is done.
  3824. */
  3825. /*
  3826. * Change a given task's CPU affinity. Migrate the thread to a
  3827. * proper CPU and schedule it away if the CPU it's executing on
  3828. * is removed from the allowed bitmask.
  3829. *
  3830. * NOTE: the caller must have a valid reference to the task, the
  3831. * task must not exit() & deallocate itself prematurely. The
  3832. * call is not atomic; no spinlocks may be held.
  3833. */
  3834. int set_cpus_allowed(task_t *p, cpumask_t new_mask)
  3835. {
  3836. unsigned long flags;
  3837. int ret = 0;
  3838. migration_req_t req;
  3839. runqueue_t *rq;
  3840. rq = task_rq_lock(p, &flags);
  3841. if (!cpus_intersects(new_mask, cpu_online_map)) {
  3842. ret = -EINVAL;
  3843. goto out;
  3844. }
  3845. p->cpus_allowed = new_mask;
  3846. /* Can the task run on the task's current CPU? If so, we're done */
  3847. if (cpu_isset(task_cpu(p), new_mask))
  3848. goto out;
  3849. if (migrate_task(p, any_online_cpu(new_mask), &req)) {
  3850. /* Need help from migration thread: drop lock and wait. */
  3851. task_rq_unlock(rq, &flags);
  3852. wake_up_process(rq->migration_thread);
  3853. wait_for_completion(&req.done);
  3854. tlb_migrate_finish(p->mm);
  3855. return 0;
  3856. }
  3857. out:
  3858. task_rq_unlock(rq, &flags);
  3859. return ret;
  3860. }
  3861. EXPORT_SYMBOL_GPL(set_cpus_allowed);
  3862. /*
  3863. * Move (not current) task off this cpu, onto dest cpu. We're doing
  3864. * this because either it can't run here any more (set_cpus_allowed()
  3865. * away from this CPU, or CPU going down), or because we're
  3866. * attempting to rebalance this task on exec (sched_exec).
  3867. *
  3868. * So we race with normal scheduler movements, but that's OK, as long
  3869. * as the task is no longer on this CPU.
  3870. */
  3871. static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
  3872. {
  3873. runqueue_t *rq_dest, *rq_src;
  3874. if (unlikely(cpu_is_offline(dest_cpu)))
  3875. return;
  3876. rq_src = cpu_rq(src_cpu);
  3877. rq_dest = cpu_rq(dest_cpu);
  3878. double_rq_lock(rq_src, rq_dest);
  3879. /* Already moved. */
  3880. if (task_cpu(p) != src_cpu)
  3881. goto out;
  3882. /* Affinity changed (again). */
  3883. if (!cpu_isset(dest_cpu, p->cpus_allowed))
  3884. goto out;
  3885. set_task_cpu(p, dest_cpu);
  3886. if (p->array) {
  3887. /*
  3888. * Sync timestamp with rq_dest's before activating.
  3889. * The same thing could be achieved by doing this step
  3890. * afterwards, and pretending it was a local activate.
  3891. * This way is cleaner and logically correct.
  3892. */
  3893. p->timestamp = p->timestamp - rq_src->timestamp_last_tick
  3894. + rq_dest->timestamp_last_tick;
  3895. deactivate_task(p, rq_src);
  3896. activate_task(p, rq_dest, 0);
  3897. if (TASK_PREEMPTS_CURR(p, rq_dest))
  3898. resched_task(rq_dest->curr);
  3899. }
  3900. out:
  3901. double_rq_unlock(rq_src, rq_dest);
  3902. }
  3903. /*
  3904. * migration_thread - this is a highprio system thread that performs
  3905. * thread migration by bumping thread off CPU then 'pushing' onto
  3906. * another runqueue.
  3907. */
  3908. static int migration_thread(void *data)
  3909. {
  3910. runqueue_t *rq;
  3911. int cpu = (long)data;
  3912. rq = cpu_rq(cpu);
  3913. BUG_ON(rq->migration_thread != current);
  3914. set_current_state(TASK_INTERRUPTIBLE);
  3915. while (!kthread_should_stop()) {
  3916. struct list_head *head;
  3917. migration_req_t *req;
  3918. try_to_freeze();
  3919. spin_lock_irq(&rq->lock);
  3920. if (cpu_is_offline(cpu)) {
  3921. spin_unlock_irq(&rq->lock);
  3922. goto wait_to_die;
  3923. }
  3924. if (rq->active_balance) {
  3925. active_load_balance(rq, cpu);
  3926. rq->active_balance = 0;
  3927. }
  3928. head = &rq->migration_queue;
  3929. if (list_empty(head)) {
  3930. spin_unlock_irq(&rq->lock);
  3931. schedule();
  3932. set_current_state(TASK_INTERRUPTIBLE);
  3933. continue;
  3934. }
  3935. req = list_entry(head->next, migration_req_t, list);
  3936. list_del_init(head->next);
  3937. spin_unlock(&rq->lock);
  3938. __migrate_task(req->task, cpu, req->dest_cpu);
  3939. local_irq_enable();
  3940. complete(&req->done);
  3941. }
  3942. __set_current_state(TASK_RUNNING);
  3943. return 0;
  3944. wait_to_die:
  3945. /* Wait for kthread_stop */
  3946. set_current_state(TASK_INTERRUPTIBLE);
  3947. while (!kthread_should_stop()) {
  3948. schedule();
  3949. set_current_state(TASK_INTERRUPTIBLE);
  3950. }
  3951. __set_current_state(TASK_RUNNING);
  3952. return 0;
  3953. }
  3954. #ifdef CONFIG_HOTPLUG_CPU
  3955. /* Figure out where task on dead CPU should go, use force if neccessary. */
  3956. static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
  3957. {
  3958. int dest_cpu;
  3959. cpumask_t mask;
  3960. /* On same node? */
  3961. mask = node_to_cpumask(cpu_to_node(dead_cpu));
  3962. cpus_and(mask, mask, tsk->cpus_allowed);
  3963. dest_cpu = any_online_cpu(mask);
  3964. /* On any allowed CPU? */
  3965. if (dest_cpu == NR_CPUS)
  3966. dest_cpu = any_online_cpu(tsk->cpus_allowed);
  3967. /* No more Mr. Nice Guy. */
  3968. if (dest_cpu == NR_CPUS) {
  3969. cpus_setall(tsk->cpus_allowed);
  3970. dest_cpu = any_online_cpu(tsk->cpus_allowed);
  3971. /*
  3972. * Don't tell them about moving exiting tasks or
  3973. * kernel threads (both mm NULL), since they never
  3974. * leave kernel.
  3975. */
  3976. if (tsk->mm && printk_ratelimit())
  3977. printk(KERN_INFO "process %d (%s) no "
  3978. "longer affine to cpu%d\n",
  3979. tsk->pid, tsk->comm, dead_cpu);
  3980. }
  3981. __migrate_task(tsk, dead_cpu, dest_cpu);
  3982. }
  3983. /*
  3984. * While a dead CPU has no uninterruptible tasks queued at this point,
  3985. * it might still have a nonzero ->nr_uninterruptible counter, because
  3986. * for performance reasons the counter is not stricly tracking tasks to
  3987. * their home CPUs. So we just add the counter to another CPU's counter,
  3988. * to keep the global sum constant after CPU-down:
  3989. */
  3990. static void migrate_nr_uninterruptible(runqueue_t *rq_src)
  3991. {
  3992. runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
  3993. unsigned long flags;
  3994. local_irq_save(flags);
  3995. double_rq_lock(rq_src, rq_dest);
  3996. rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
  3997. rq_src->nr_uninterruptible = 0;
  3998. double_rq_unlock(rq_src, rq_dest);
  3999. local_irq_restore(flags);
  4000. }
  4001. /* Run through task list and migrate tasks from the dead cpu. */
  4002. static void migrate_live_tasks(int src_cpu)
  4003. {
  4004. struct task_struct *tsk, *t;
  4005. write_lock_irq(&tasklist_lock);
  4006. do_each_thread(t, tsk) {
  4007. if (tsk == current)
  4008. continue;
  4009. if (task_cpu(tsk) == src_cpu)
  4010. move_task_off_dead_cpu(src_cpu, tsk);
  4011. } while_each_thread(t, tsk);
  4012. write_unlock_irq(&tasklist_lock);
  4013. }
  4014. /* Schedules idle task to be the next runnable task on current CPU.
  4015. * It does so by boosting its priority to highest possible and adding it to
  4016. * the _front_ of runqueue. Used by CPU offline code.
  4017. */
  4018. void sched_idle_next(void)
  4019. {
  4020. int cpu = smp_processor_id();
  4021. runqueue_t *rq = this_rq();
  4022. struct task_struct *p = rq->idle;
  4023. unsigned long flags;
  4024. /* cpu has to be offline */
  4025. BUG_ON(cpu_online(cpu));
  4026. /* Strictly not necessary since rest of the CPUs are stopped by now
  4027. * and interrupts disabled on current cpu.
  4028. */
  4029. spin_lock_irqsave(&rq->lock, flags);
  4030. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  4031. /* Add idle task to _front_ of it's priority queue */
  4032. __activate_idle_task(p, rq);
  4033. spin_unlock_irqrestore(&rq->lock, flags);
  4034. }
  4035. /* Ensures that the idle task is using init_mm right before its cpu goes
  4036. * offline.
  4037. */
  4038. void idle_task_exit(void)
  4039. {
  4040. struct mm_struct *mm = current->active_mm;
  4041. BUG_ON(cpu_online(smp_processor_id()));
  4042. if (mm != &init_mm)
  4043. switch_mm(mm, &init_mm, current);
  4044. mmdrop(mm);
  4045. }
  4046. static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
  4047. {
  4048. struct runqueue *rq = cpu_rq(dead_cpu);
  4049. /* Must be exiting, otherwise would be on tasklist. */
  4050. BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
  4051. /* Cannot have done final schedule yet: would have vanished. */
  4052. BUG_ON(tsk->flags & PF_DEAD);
  4053. get_task_struct(tsk);
  4054. /*
  4055. * Drop lock around migration; if someone else moves it,
  4056. * that's OK. No task can be added to this CPU, so iteration is
  4057. * fine.
  4058. */
  4059. spin_unlock_irq(&rq->lock);
  4060. move_task_off_dead_cpu(dead_cpu, tsk);
  4061. spin_lock_irq(&rq->lock);
  4062. put_task_struct(tsk);
  4063. }
  4064. /* release_task() removes task from tasklist, so we won't find dead tasks. */
  4065. static void migrate_dead_tasks(unsigned int dead_cpu)
  4066. {
  4067. unsigned arr, i;
  4068. struct runqueue *rq = cpu_rq(dead_cpu);
  4069. for (arr = 0; arr < 2; arr++) {
  4070. for (i = 0; i < MAX_PRIO; i++) {
  4071. struct list_head *list = &rq->arrays[arr].queue[i];
  4072. while (!list_empty(list))
  4073. migrate_dead(dead_cpu,
  4074. list_entry(list->next, task_t,
  4075. run_list));
  4076. }
  4077. }
  4078. }
  4079. #endif /* CONFIG_HOTPLUG_CPU */
  4080. /*
  4081. * migration_call - callback that gets triggered when a CPU is added.
  4082. * Here we can start up the necessary migration thread for the new CPU.
  4083. */
  4084. static int migration_call(struct notifier_block *nfb, unsigned long action,
  4085. void *hcpu)
  4086. {
  4087. int cpu = (long)hcpu;
  4088. struct task_struct *p;
  4089. struct runqueue *rq;
  4090. unsigned long flags;
  4091. switch (action) {
  4092. case CPU_UP_PREPARE:
  4093. p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
  4094. if (IS_ERR(p))
  4095. return NOTIFY_BAD;
  4096. p->flags |= PF_NOFREEZE;
  4097. kthread_bind(p, cpu);
  4098. /* Must be high prio: stop_machine expects to yield to it. */
  4099. rq = task_rq_lock(p, &flags);
  4100. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  4101. task_rq_unlock(rq, &flags);
  4102. cpu_rq(cpu)->migration_thread = p;
  4103. break;
  4104. case CPU_ONLINE:
  4105. /* Strictly unneccessary, as first user will wake it. */
  4106. wake_up_process(cpu_rq(cpu)->migration_thread);
  4107. break;
  4108. #ifdef CONFIG_HOTPLUG_CPU
  4109. case CPU_UP_CANCELED:
  4110. /* Unbind it from offline cpu so it can run. Fall thru. */
  4111. kthread_bind(cpu_rq(cpu)->migration_thread,
  4112. any_online_cpu(cpu_online_map));
  4113. kthread_stop(cpu_rq(cpu)->migration_thread);
  4114. cpu_rq(cpu)->migration_thread = NULL;
  4115. break;
  4116. case CPU_DEAD:
  4117. migrate_live_tasks(cpu);
  4118. rq = cpu_rq(cpu);
  4119. kthread_stop(rq->migration_thread);
  4120. rq->migration_thread = NULL;
  4121. /* Idle task back to normal (off runqueue, low prio) */
  4122. rq = task_rq_lock(rq->idle, &flags);
  4123. deactivate_task(rq->idle, rq);
  4124. rq->idle->static_prio = MAX_PRIO;
  4125. __setscheduler(rq->idle, SCHED_NORMAL, 0);
  4126. migrate_dead_tasks(cpu);
  4127. task_rq_unlock(rq, &flags);
  4128. migrate_nr_uninterruptible(rq);
  4129. BUG_ON(rq->nr_running != 0);
  4130. /* No need to migrate the tasks: it was best-effort if
  4131. * they didn't do lock_cpu_hotplug(). Just wake up
  4132. * the requestors. */
  4133. spin_lock_irq(&rq->lock);
  4134. while (!list_empty(&rq->migration_queue)) {
  4135. migration_req_t *req;
  4136. req = list_entry(rq->migration_queue.next,
  4137. migration_req_t, list);
  4138. list_del_init(&req->list);
  4139. complete(&req->done);
  4140. }
  4141. spin_unlock_irq(&rq->lock);
  4142. break;
  4143. #endif
  4144. }
  4145. return NOTIFY_OK;
  4146. }
  4147. /* Register at highest priority so that task migration (migrate_all_tasks)
  4148. * happens before everything else.
  4149. */
  4150. static struct notifier_block __devinitdata migration_notifier = {
  4151. .notifier_call = migration_call,
  4152. .priority = 10
  4153. };
  4154. int __init migration_init(void)
  4155. {
  4156. void *cpu = (void *)(long)smp_processor_id();
  4157. /* Start one for boot CPU. */
  4158. migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
  4159. migration_call(&migration_notifier, CPU_ONLINE, cpu);
  4160. register_cpu_notifier(&migration_notifier);
  4161. return 0;
  4162. }
  4163. #endif
  4164. #ifdef CONFIG_SMP
  4165. #undef SCHED_DOMAIN_DEBUG
  4166. #ifdef SCHED_DOMAIN_DEBUG
  4167. static void sched_domain_debug(struct sched_domain *sd, int cpu)
  4168. {
  4169. int level = 0;
  4170. if (!sd) {
  4171. printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
  4172. return;
  4173. }
  4174. printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
  4175. do {
  4176. int i;
  4177. char str[NR_CPUS];
  4178. struct sched_group *group = sd->groups;
  4179. cpumask_t groupmask;
  4180. cpumask_scnprintf(str, NR_CPUS, sd->span);
  4181. cpus_clear(groupmask);
  4182. printk(KERN_DEBUG);
  4183. for (i = 0; i < level + 1; i++)
  4184. printk(" ");
  4185. printk("domain %d: ", level);
  4186. if (!(sd->flags & SD_LOAD_BALANCE)) {
  4187. printk("does not load-balance\n");
  4188. if (sd->parent)
  4189. printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
  4190. break;
  4191. }
  4192. printk("span %s\n", str);
  4193. if (!cpu_isset(cpu, sd->span))
  4194. printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
  4195. if (!cpu_isset(cpu, group->cpumask))
  4196. printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
  4197. printk(KERN_DEBUG);
  4198. for (i = 0; i < level + 2; i++)
  4199. printk(" ");
  4200. printk("groups:");
  4201. do {
  4202. if (!group) {
  4203. printk("\n");
  4204. printk(KERN_ERR "ERROR: group is NULL\n");
  4205. break;
  4206. }
  4207. if (!group->cpu_power) {
  4208. printk("\n");
  4209. printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
  4210. }
  4211. if (!cpus_weight(group->cpumask)) {
  4212. printk("\n");
  4213. printk(KERN_ERR "ERROR: empty group\n");
  4214. }
  4215. if (cpus_intersects(groupmask, group->cpumask)) {
  4216. printk("\n");
  4217. printk(KERN_ERR "ERROR: repeated CPUs\n");
  4218. }
  4219. cpus_or(groupmask, groupmask, group->cpumask);
  4220. cpumask_scnprintf(str, NR_CPUS, group->cpumask);
  4221. printk(" %s", str);
  4222. group = group->next;
  4223. } while (group != sd->groups);
  4224. printk("\n");
  4225. if (!cpus_equal(sd->span, groupmask))
  4226. printk(KERN_ERR "ERROR: groups don't span domain->span\n");
  4227. level++;
  4228. sd = sd->parent;
  4229. if (sd) {
  4230. if (!cpus_subset(groupmask, sd->span))
  4231. printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
  4232. }
  4233. } while (sd);
  4234. }
  4235. #else
  4236. #define sched_domain_debug(sd, cpu) {}
  4237. #endif
  4238. static int sd_degenerate(struct sched_domain *sd)
  4239. {
  4240. if (cpus_weight(sd->span) == 1)
  4241. return 1;
  4242. /* Following flags need at least 2 groups */
  4243. if (sd->flags & (SD_LOAD_BALANCE |
  4244. SD_BALANCE_NEWIDLE |
  4245. SD_BALANCE_FORK |
  4246. SD_BALANCE_EXEC)) {
  4247. if (sd->groups != sd->groups->next)
  4248. return 0;
  4249. }
  4250. /* Following flags don't use groups */
  4251. if (sd->flags & (SD_WAKE_IDLE |
  4252. SD_WAKE_AFFINE |
  4253. SD_WAKE_BALANCE))
  4254. return 0;
  4255. return 1;
  4256. }
  4257. static int sd_parent_degenerate(struct sched_domain *sd,
  4258. struct sched_domain *parent)
  4259. {
  4260. unsigned long cflags = sd->flags, pflags = parent->flags;
  4261. if (sd_degenerate(parent))
  4262. return 1;
  4263. if (!cpus_equal(sd->span, parent->span))
  4264. return 0;
  4265. /* Does parent contain flags not in child? */
  4266. /* WAKE_BALANCE is a subset of WAKE_AFFINE */
  4267. if (cflags & SD_WAKE_AFFINE)
  4268. pflags &= ~SD_WAKE_BALANCE;
  4269. /* Flags needing groups don't count if only 1 group in parent */
  4270. if (parent->groups == parent->groups->next) {
  4271. pflags &= ~(SD_LOAD_BALANCE |
  4272. SD_BALANCE_NEWIDLE |
  4273. SD_BALANCE_FORK |
  4274. SD_BALANCE_EXEC);
  4275. }
  4276. if (~cflags & pflags)
  4277. return 0;
  4278. return 1;
  4279. }
  4280. /*
  4281. * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
  4282. * hold the hotplug lock.
  4283. */
  4284. static void cpu_attach_domain(struct sched_domain *sd, int cpu)
  4285. {
  4286. runqueue_t *rq = cpu_rq(cpu);
  4287. struct sched_domain *tmp;
  4288. /* Remove the sched domains which do not contribute to scheduling. */
  4289. for (tmp = sd; tmp; tmp = tmp->parent) {
  4290. struct sched_domain *parent = tmp->parent;
  4291. if (!parent)
  4292. break;
  4293. if (sd_parent_degenerate(tmp, parent))
  4294. tmp->parent = parent->parent;
  4295. }
  4296. if (sd && sd_degenerate(sd))
  4297. sd = sd->parent;
  4298. sched_domain_debug(sd, cpu);
  4299. rcu_assign_pointer(rq->sd, sd);
  4300. }
  4301. /* cpus with isolated domains */
  4302. static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
  4303. /* Setup the mask of cpus configured for isolated domains */
  4304. static int __init isolated_cpu_setup(char *str)
  4305. {
  4306. int ints[NR_CPUS], i;
  4307. str = get_options(str, ARRAY_SIZE(ints), ints);
  4308. cpus_clear(cpu_isolated_map);
  4309. for (i = 1; i <= ints[0]; i++)
  4310. if (ints[i] < NR_CPUS)
  4311. cpu_set(ints[i], cpu_isolated_map);
  4312. return 1;
  4313. }
  4314. __setup ("isolcpus=", isolated_cpu_setup);
  4315. /*
  4316. * init_sched_build_groups takes an array of groups, the cpumask we wish
  4317. * to span, and a pointer to a function which identifies what group a CPU
  4318. * belongs to. The return value of group_fn must be a valid index into the
  4319. * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
  4320. * keep track of groups covered with a cpumask_t).
  4321. *
  4322. * init_sched_build_groups will build a circular linked list of the groups
  4323. * covered by the given span, and will set each group's ->cpumask correctly,
  4324. * and ->cpu_power to 0.
  4325. */
  4326. static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
  4327. int (*group_fn)(int cpu))
  4328. {
  4329. struct sched_group *first = NULL, *last = NULL;
  4330. cpumask_t covered = CPU_MASK_NONE;
  4331. int i;
  4332. for_each_cpu_mask(i, span) {
  4333. int group = group_fn(i);
  4334. struct sched_group *sg = &groups[group];
  4335. int j;
  4336. if (cpu_isset(i, covered))
  4337. continue;
  4338. sg->cpumask = CPU_MASK_NONE;
  4339. sg->cpu_power = 0;
  4340. for_each_cpu_mask(j, span) {
  4341. if (group_fn(j) != group)
  4342. continue;
  4343. cpu_set(j, covered);
  4344. cpu_set(j, sg->cpumask);
  4345. }
  4346. if (!first)
  4347. first = sg;
  4348. if (last)
  4349. last->next = sg;
  4350. last = sg;
  4351. }
  4352. last->next = first;
  4353. }
  4354. #define SD_NODES_PER_DOMAIN 16
  4355. /*
  4356. * Self-tuning task migration cost measurement between source and target CPUs.
  4357. *
  4358. * This is done by measuring the cost of manipulating buffers of varying
  4359. * sizes. For a given buffer-size here are the steps that are taken:
  4360. *
  4361. * 1) the source CPU reads+dirties a shared buffer
  4362. * 2) the target CPU reads+dirties the same shared buffer
  4363. *
  4364. * We measure how long they take, in the following 4 scenarios:
  4365. *
  4366. * - source: CPU1, target: CPU2 | cost1
  4367. * - source: CPU2, target: CPU1 | cost2
  4368. * - source: CPU1, target: CPU1 | cost3
  4369. * - source: CPU2, target: CPU2 | cost4
  4370. *
  4371. * We then calculate the cost3+cost4-cost1-cost2 difference - this is
  4372. * the cost of migration.
  4373. *
  4374. * We then start off from a small buffer-size and iterate up to larger
  4375. * buffer sizes, in 5% steps - measuring each buffer-size separately, and
  4376. * doing a maximum search for the cost. (The maximum cost for a migration
  4377. * normally occurs when the working set size is around the effective cache
  4378. * size.)
  4379. */
  4380. #define SEARCH_SCOPE 2
  4381. #define MIN_CACHE_SIZE (64*1024U)
  4382. #define DEFAULT_CACHE_SIZE (5*1024*1024U)
  4383. #define ITERATIONS 1
  4384. #define SIZE_THRESH 130
  4385. #define COST_THRESH 130
  4386. /*
  4387. * The migration cost is a function of 'domain distance'. Domain
  4388. * distance is the number of steps a CPU has to iterate down its
  4389. * domain tree to share a domain with the other CPU. The farther
  4390. * two CPUs are from each other, the larger the distance gets.
  4391. *
  4392. * Note that we use the distance only to cache measurement results,
  4393. * the distance value is not used numerically otherwise. When two
  4394. * CPUs have the same distance it is assumed that the migration
  4395. * cost is the same. (this is a simplification but quite practical)
  4396. */
  4397. #define MAX_DOMAIN_DISTANCE 32
  4398. static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
  4399. { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] = -1LL };
  4400. /*
  4401. * Allow override of migration cost - in units of microseconds.
  4402. * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
  4403. * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
  4404. */
  4405. static int __init migration_cost_setup(char *str)
  4406. {
  4407. int ints[MAX_DOMAIN_DISTANCE+1], i;
  4408. str = get_options(str, ARRAY_SIZE(ints), ints);
  4409. printk("#ints: %d\n", ints[0]);
  4410. for (i = 1; i <= ints[0]; i++) {
  4411. migration_cost[i-1] = (unsigned long long)ints[i]*1000;
  4412. printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
  4413. }
  4414. return 1;
  4415. }
  4416. __setup ("migration_cost=", migration_cost_setup);
  4417. /*
  4418. * Global multiplier (divisor) for migration-cutoff values,
  4419. * in percentiles. E.g. use a value of 150 to get 1.5 times
  4420. * longer cache-hot cutoff times.
  4421. *
  4422. * (We scale it from 100 to 128 to long long handling easier.)
  4423. */
  4424. #define MIGRATION_FACTOR_SCALE 128
  4425. static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
  4426. static int __init setup_migration_factor(char *str)
  4427. {
  4428. get_option(&str, &migration_factor);
  4429. migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
  4430. return 1;
  4431. }
  4432. __setup("migration_factor=", setup_migration_factor);
  4433. /*
  4434. * Estimated distance of two CPUs, measured via the number of domains
  4435. * we have to pass for the two CPUs to be in the same span:
  4436. */
  4437. static unsigned long domain_distance(int cpu1, int cpu2)
  4438. {
  4439. unsigned long distance = 0;
  4440. struct sched_domain *sd;
  4441. for_each_domain(cpu1, sd) {
  4442. WARN_ON(!cpu_isset(cpu1, sd->span));
  4443. if (cpu_isset(cpu2, sd->span))
  4444. return distance;
  4445. distance++;
  4446. }
  4447. if (distance >= MAX_DOMAIN_DISTANCE) {
  4448. WARN_ON(1);
  4449. distance = MAX_DOMAIN_DISTANCE-1;
  4450. }
  4451. return distance;
  4452. }
  4453. static unsigned int migration_debug;
  4454. static int __init setup_migration_debug(char *str)
  4455. {
  4456. get_option(&str, &migration_debug);
  4457. return 1;
  4458. }
  4459. __setup("migration_debug=", setup_migration_debug);
  4460. /*
  4461. * Maximum cache-size that the scheduler should try to measure.
  4462. * Architectures with larger caches should tune this up during
  4463. * bootup. Gets used in the domain-setup code (i.e. during SMP
  4464. * bootup).
  4465. */
  4466. unsigned int max_cache_size;
  4467. static int __init setup_max_cache_size(char *str)
  4468. {
  4469. get_option(&str, &max_cache_size);
  4470. return 1;
  4471. }
  4472. __setup("max_cache_size=", setup_max_cache_size);
  4473. /*
  4474. * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
  4475. * is the operation that is timed, so we try to generate unpredictable
  4476. * cachemisses that still end up filling the L2 cache:
  4477. */
  4478. static void touch_cache(void *__cache, unsigned long __size)
  4479. {
  4480. unsigned long size = __size/sizeof(long), chunk1 = size/3,
  4481. chunk2 = 2*size/3;
  4482. unsigned long *cache = __cache;
  4483. int i;
  4484. for (i = 0; i < size/6; i += 8) {
  4485. switch (i % 6) {
  4486. case 0: cache[i]++;
  4487. case 1: cache[size-1-i]++;
  4488. case 2: cache[chunk1-i]++;
  4489. case 3: cache[chunk1+i]++;
  4490. case 4: cache[chunk2-i]++;
  4491. case 5: cache[chunk2+i]++;
  4492. }
  4493. }
  4494. }
  4495. /*
  4496. * Measure the cache-cost of one task migration. Returns in units of nsec.
  4497. */
  4498. static unsigned long long measure_one(void *cache, unsigned long size,
  4499. int source, int target)
  4500. {
  4501. cpumask_t mask, saved_mask;
  4502. unsigned long long t0, t1, t2, t3, cost;
  4503. saved_mask = current->cpus_allowed;
  4504. /*
  4505. * Flush source caches to RAM and invalidate them:
  4506. */
  4507. sched_cacheflush();
  4508. /*
  4509. * Migrate to the source CPU:
  4510. */
  4511. mask = cpumask_of_cpu(source);
  4512. set_cpus_allowed(current, mask);
  4513. WARN_ON(smp_processor_id() != source);
  4514. /*
  4515. * Dirty the working set:
  4516. */
  4517. t0 = sched_clock();
  4518. touch_cache(cache, size);
  4519. t1 = sched_clock();
  4520. /*
  4521. * Migrate to the target CPU, dirty the L2 cache and access
  4522. * the shared buffer. (which represents the working set
  4523. * of a migrated task.)
  4524. */
  4525. mask = cpumask_of_cpu(target);
  4526. set_cpus_allowed(current, mask);
  4527. WARN_ON(smp_processor_id() != target);
  4528. t2 = sched_clock();
  4529. touch_cache(cache, size);
  4530. t3 = sched_clock();
  4531. cost = t1-t0 + t3-t2;
  4532. if (migration_debug >= 2)
  4533. printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
  4534. source, target, t1-t0, t1-t0, t3-t2, cost);
  4535. /*
  4536. * Flush target caches to RAM and invalidate them:
  4537. */
  4538. sched_cacheflush();
  4539. set_cpus_allowed(current, saved_mask);
  4540. return cost;
  4541. }
  4542. /*
  4543. * Measure a series of task migrations and return the average
  4544. * result. Since this code runs early during bootup the system
  4545. * is 'undisturbed' and the average latency makes sense.
  4546. *
  4547. * The algorithm in essence auto-detects the relevant cache-size,
  4548. * so it will properly detect different cachesizes for different
  4549. * cache-hierarchies, depending on how the CPUs are connected.
  4550. *
  4551. * Architectures can prime the upper limit of the search range via
  4552. * max_cache_size, otherwise the search range defaults to 20MB...64K.
  4553. */
  4554. static unsigned long long
  4555. measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
  4556. {
  4557. unsigned long long cost1, cost2;
  4558. int i;
  4559. /*
  4560. * Measure the migration cost of 'size' bytes, over an
  4561. * average of 10 runs:
  4562. *
  4563. * (We perturb the cache size by a small (0..4k)
  4564. * value to compensate size/alignment related artifacts.
  4565. * We also subtract the cost of the operation done on
  4566. * the same CPU.)
  4567. */
  4568. cost1 = 0;
  4569. /*
  4570. * dry run, to make sure we start off cache-cold on cpu1,
  4571. * and to get any vmalloc pagefaults in advance:
  4572. */
  4573. measure_one(cache, size, cpu1, cpu2);
  4574. for (i = 0; i < ITERATIONS; i++)
  4575. cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
  4576. measure_one(cache, size, cpu2, cpu1);
  4577. for (i = 0; i < ITERATIONS; i++)
  4578. cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
  4579. /*
  4580. * (We measure the non-migrating [cached] cost on both
  4581. * cpu1 and cpu2, to handle CPUs with different speeds)
  4582. */
  4583. cost2 = 0;
  4584. measure_one(cache, size, cpu1, cpu1);
  4585. for (i = 0; i < ITERATIONS; i++)
  4586. cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
  4587. measure_one(cache, size, cpu2, cpu2);
  4588. for (i = 0; i < ITERATIONS; i++)
  4589. cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
  4590. /*
  4591. * Get the per-iteration migration cost:
  4592. */
  4593. do_div(cost1, 2*ITERATIONS);
  4594. do_div(cost2, 2*ITERATIONS);
  4595. return cost1 - cost2;
  4596. }
  4597. static unsigned long long measure_migration_cost(int cpu1, int cpu2)
  4598. {
  4599. unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
  4600. unsigned int max_size, size, size_found = 0;
  4601. long long cost = 0, prev_cost;
  4602. void *cache;
  4603. /*
  4604. * Search from max_cache_size*5 down to 64K - the real relevant
  4605. * cachesize has to lie somewhere inbetween.
  4606. */
  4607. if (max_cache_size) {
  4608. max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
  4609. size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
  4610. } else {
  4611. /*
  4612. * Since we have no estimation about the relevant
  4613. * search range
  4614. */
  4615. max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
  4616. size = MIN_CACHE_SIZE;
  4617. }
  4618. if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
  4619. printk("cpu %d and %d not both online!\n", cpu1, cpu2);
  4620. return 0;
  4621. }
  4622. /*
  4623. * Allocate the working set:
  4624. */
  4625. cache = vmalloc(max_size);
  4626. if (!cache) {
  4627. printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
  4628. return 1000000; // return 1 msec on very small boxen
  4629. }
  4630. while (size <= max_size) {
  4631. prev_cost = cost;
  4632. cost = measure_cost(cpu1, cpu2, cache, size);
  4633. /*
  4634. * Update the max:
  4635. */
  4636. if (cost > 0) {
  4637. if (max_cost < cost) {
  4638. max_cost = cost;
  4639. size_found = size;
  4640. }
  4641. }
  4642. /*
  4643. * Calculate average fluctuation, we use this to prevent
  4644. * noise from triggering an early break out of the loop:
  4645. */
  4646. fluct = abs(cost - prev_cost);
  4647. avg_fluct = (avg_fluct + fluct)/2;
  4648. if (migration_debug)
  4649. printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
  4650. cpu1, cpu2, size,
  4651. (long)cost / 1000000,
  4652. ((long)cost / 100000) % 10,
  4653. (long)max_cost / 1000000,
  4654. ((long)max_cost / 100000) % 10,
  4655. domain_distance(cpu1, cpu2),
  4656. cost, avg_fluct);
  4657. /*
  4658. * If we iterated at least 20% past the previous maximum,
  4659. * and the cost has dropped by more than 20% already,
  4660. * (taking fluctuations into account) then we assume to
  4661. * have found the maximum and break out of the loop early:
  4662. */
  4663. if (size_found && (size*100 > size_found*SIZE_THRESH))
  4664. if (cost+avg_fluct <= 0 ||
  4665. max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
  4666. if (migration_debug)
  4667. printk("-> found max.\n");
  4668. break;
  4669. }
  4670. /*
  4671. * Increase the cachesize in 10% steps:
  4672. */
  4673. size = size * 10 / 9;
  4674. }
  4675. if (migration_debug)
  4676. printk("[%d][%d] working set size found: %d, cost: %Ld\n",
  4677. cpu1, cpu2, size_found, max_cost);
  4678. vfree(cache);
  4679. /*
  4680. * A task is considered 'cache cold' if at least 2 times
  4681. * the worst-case cost of migration has passed.
  4682. *
  4683. * (this limit is only listened to if the load-balancing
  4684. * situation is 'nice' - if there is a large imbalance we
  4685. * ignore it for the sake of CPU utilization and
  4686. * processing fairness.)
  4687. */
  4688. return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
  4689. }
  4690. static void calibrate_migration_costs(const cpumask_t *cpu_map)
  4691. {
  4692. int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
  4693. unsigned long j0, j1, distance, max_distance = 0;
  4694. struct sched_domain *sd;
  4695. j0 = jiffies;
  4696. /*
  4697. * First pass - calculate the cacheflush times:
  4698. */
  4699. for_each_cpu_mask(cpu1, *cpu_map) {
  4700. for_each_cpu_mask(cpu2, *cpu_map) {
  4701. if (cpu1 == cpu2)
  4702. continue;
  4703. distance = domain_distance(cpu1, cpu2);
  4704. max_distance = max(max_distance, distance);
  4705. /*
  4706. * No result cached yet?
  4707. */
  4708. if (migration_cost[distance] == -1LL)
  4709. migration_cost[distance] =
  4710. measure_migration_cost(cpu1, cpu2);
  4711. }
  4712. }
  4713. /*
  4714. * Second pass - update the sched domain hierarchy with
  4715. * the new cache-hot-time estimations:
  4716. */
  4717. for_each_cpu_mask(cpu, *cpu_map) {
  4718. distance = 0;
  4719. for_each_domain(cpu, sd) {
  4720. sd->cache_hot_time = migration_cost[distance];
  4721. distance++;
  4722. }
  4723. }
  4724. /*
  4725. * Print the matrix:
  4726. */
  4727. if (migration_debug)
  4728. printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
  4729. max_cache_size,
  4730. #ifdef CONFIG_X86
  4731. cpu_khz/1000
  4732. #else
  4733. -1
  4734. #endif
  4735. );
  4736. if (system_state == SYSTEM_BOOTING) {
  4737. printk("migration_cost=");
  4738. for (distance = 0; distance <= max_distance; distance++) {
  4739. if (distance)
  4740. printk(",");
  4741. printk("%ld", (long)migration_cost[distance] / 1000);
  4742. }
  4743. printk("\n");
  4744. }
  4745. j1 = jiffies;
  4746. if (migration_debug)
  4747. printk("migration: %ld seconds\n", (j1-j0)/HZ);
  4748. /*
  4749. * Move back to the original CPU. NUMA-Q gets confused
  4750. * if we migrate to another quad during bootup.
  4751. */
  4752. if (raw_smp_processor_id() != orig_cpu) {
  4753. cpumask_t mask = cpumask_of_cpu(orig_cpu),
  4754. saved_mask = current->cpus_allowed;
  4755. set_cpus_allowed(current, mask);
  4756. set_cpus_allowed(current, saved_mask);
  4757. }
  4758. }
  4759. #ifdef CONFIG_NUMA
  4760. /**
  4761. * find_next_best_node - find the next node to include in a sched_domain
  4762. * @node: node whose sched_domain we're building
  4763. * @used_nodes: nodes already in the sched_domain
  4764. *
  4765. * Find the next node to include in a given scheduling domain. Simply
  4766. * finds the closest node not already in the @used_nodes map.
  4767. *
  4768. * Should use nodemask_t.
  4769. */
  4770. static int find_next_best_node(int node, unsigned long *used_nodes)
  4771. {
  4772. int i, n, val, min_val, best_node = 0;
  4773. min_val = INT_MAX;
  4774. for (i = 0; i < MAX_NUMNODES; i++) {
  4775. /* Start at @node */
  4776. n = (node + i) % MAX_NUMNODES;
  4777. if (!nr_cpus_node(n))
  4778. continue;
  4779. /* Skip already used nodes */
  4780. if (test_bit(n, used_nodes))
  4781. continue;
  4782. /* Simple min distance search */
  4783. val = node_distance(node, n);
  4784. if (val < min_val) {
  4785. min_val = val;
  4786. best_node = n;
  4787. }
  4788. }
  4789. set_bit(best_node, used_nodes);
  4790. return best_node;
  4791. }
  4792. /**
  4793. * sched_domain_node_span - get a cpumask for a node's sched_domain
  4794. * @node: node whose cpumask we're constructing
  4795. * @size: number of nodes to include in this span
  4796. *
  4797. * Given a node, construct a good cpumask for its sched_domain to span. It
  4798. * should be one that prevents unnecessary balancing, but also spreads tasks
  4799. * out optimally.
  4800. */
  4801. static cpumask_t sched_domain_node_span(int node)
  4802. {
  4803. int i;
  4804. cpumask_t span, nodemask;
  4805. DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
  4806. cpus_clear(span);
  4807. bitmap_zero(used_nodes, MAX_NUMNODES);
  4808. nodemask = node_to_cpumask(node);
  4809. cpus_or(span, span, nodemask);
  4810. set_bit(node, used_nodes);
  4811. for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
  4812. int next_node = find_next_best_node(node, used_nodes);
  4813. nodemask = node_to_cpumask(next_node);
  4814. cpus_or(span, span, nodemask);
  4815. }
  4816. return span;
  4817. }
  4818. #endif
  4819. /*
  4820. * At the moment, CONFIG_SCHED_SMT is never defined, but leave it in so we
  4821. * can switch it on easily if needed.
  4822. */
  4823. #ifdef CONFIG_SCHED_SMT
  4824. static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
  4825. static struct sched_group sched_group_cpus[NR_CPUS];
  4826. static int cpu_to_cpu_group(int cpu)
  4827. {
  4828. return cpu;
  4829. }
  4830. #endif
  4831. static DEFINE_PER_CPU(struct sched_domain, phys_domains);
  4832. static struct sched_group sched_group_phys[NR_CPUS];
  4833. static int cpu_to_phys_group(int cpu)
  4834. {
  4835. #ifdef CONFIG_SCHED_SMT
  4836. return first_cpu(cpu_sibling_map[cpu]);
  4837. #else
  4838. return cpu;
  4839. #endif
  4840. }
  4841. #ifdef CONFIG_NUMA
  4842. /*
  4843. * The init_sched_build_groups can't handle what we want to do with node
  4844. * groups, so roll our own. Now each node has its own list of groups which
  4845. * gets dynamically allocated.
  4846. */
  4847. static DEFINE_PER_CPU(struct sched_domain, node_domains);
  4848. static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
  4849. static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
  4850. static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
  4851. static int cpu_to_allnodes_group(int cpu)
  4852. {
  4853. return cpu_to_node(cpu);
  4854. }
  4855. #endif
  4856. /*
  4857. * Build sched domains for a given set of cpus and attach the sched domains
  4858. * to the individual cpus
  4859. */
  4860. void build_sched_domains(const cpumask_t *cpu_map)
  4861. {
  4862. int i;
  4863. #ifdef CONFIG_NUMA
  4864. struct sched_group **sched_group_nodes = NULL;
  4865. struct sched_group *sched_group_allnodes = NULL;
  4866. /*
  4867. * Allocate the per-node list of sched groups
  4868. */
  4869. sched_group_nodes = kmalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
  4870. GFP_ATOMIC);
  4871. if (!sched_group_nodes) {
  4872. printk(KERN_WARNING "Can not alloc sched group node list\n");
  4873. return;
  4874. }
  4875. sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
  4876. #endif
  4877. /*
  4878. * Set up domains for cpus specified by the cpu_map.
  4879. */
  4880. for_each_cpu_mask(i, *cpu_map) {
  4881. int group;
  4882. struct sched_domain *sd = NULL, *p;
  4883. cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
  4884. cpus_and(nodemask, nodemask, *cpu_map);
  4885. #ifdef CONFIG_NUMA
  4886. if (cpus_weight(*cpu_map)
  4887. > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
  4888. if (!sched_group_allnodes) {
  4889. sched_group_allnodes
  4890. = kmalloc(sizeof(struct sched_group)
  4891. * MAX_NUMNODES,
  4892. GFP_KERNEL);
  4893. if (!sched_group_allnodes) {
  4894. printk(KERN_WARNING
  4895. "Can not alloc allnodes sched group\n");
  4896. break;
  4897. }
  4898. sched_group_allnodes_bycpu[i]
  4899. = sched_group_allnodes;
  4900. }
  4901. sd = &per_cpu(allnodes_domains, i);
  4902. *sd = SD_ALLNODES_INIT;
  4903. sd->span = *cpu_map;
  4904. group = cpu_to_allnodes_group(i);
  4905. sd->groups = &sched_group_allnodes[group];
  4906. p = sd;
  4907. } else
  4908. p = NULL;
  4909. sd = &per_cpu(node_domains, i);
  4910. *sd = SD_NODE_INIT;
  4911. sd->span = sched_domain_node_span(cpu_to_node(i));
  4912. sd->parent = p;
  4913. cpus_and(sd->span, sd->span, *cpu_map);
  4914. #endif
  4915. p = sd;
  4916. sd = &per_cpu(phys_domains, i);
  4917. group = cpu_to_phys_group(i);
  4918. *sd = SD_CPU_INIT;
  4919. sd->span = nodemask;
  4920. sd->parent = p;
  4921. sd->groups = &sched_group_phys[group];
  4922. #ifdef CONFIG_SCHED_SMT
  4923. p = sd;
  4924. sd = &per_cpu(cpu_domains, i);
  4925. group = cpu_to_cpu_group(i);
  4926. *sd = SD_SIBLING_INIT;
  4927. sd->span = cpu_sibling_map[i];
  4928. cpus_and(sd->span, sd->span, *cpu_map);
  4929. sd->parent = p;
  4930. sd->groups = &sched_group_cpus[group];
  4931. #endif
  4932. }
  4933. #ifdef CONFIG_SCHED_SMT
  4934. /* Set up CPU (sibling) groups */
  4935. for_each_cpu_mask(i, *cpu_map) {
  4936. cpumask_t this_sibling_map = cpu_sibling_map[i];
  4937. cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
  4938. if (i != first_cpu(this_sibling_map))
  4939. continue;
  4940. init_sched_build_groups(sched_group_cpus, this_sibling_map,
  4941. &cpu_to_cpu_group);
  4942. }
  4943. #endif
  4944. /* Set up physical groups */
  4945. for (i = 0; i < MAX_NUMNODES; i++) {
  4946. cpumask_t nodemask = node_to_cpumask(i);
  4947. cpus_and(nodemask, nodemask, *cpu_map);
  4948. if (cpus_empty(nodemask))
  4949. continue;
  4950. init_sched_build_groups(sched_group_phys, nodemask,
  4951. &cpu_to_phys_group);
  4952. }
  4953. #ifdef CONFIG_NUMA
  4954. /* Set up node groups */
  4955. if (sched_group_allnodes)
  4956. init_sched_build_groups(sched_group_allnodes, *cpu_map,
  4957. &cpu_to_allnodes_group);
  4958. for (i = 0; i < MAX_NUMNODES; i++) {
  4959. /* Set up node groups */
  4960. struct sched_group *sg, *prev;
  4961. cpumask_t nodemask = node_to_cpumask(i);
  4962. cpumask_t domainspan;
  4963. cpumask_t covered = CPU_MASK_NONE;
  4964. int j;
  4965. cpus_and(nodemask, nodemask, *cpu_map);
  4966. if (cpus_empty(nodemask)) {
  4967. sched_group_nodes[i] = NULL;
  4968. continue;
  4969. }
  4970. domainspan = sched_domain_node_span(i);
  4971. cpus_and(domainspan, domainspan, *cpu_map);
  4972. sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
  4973. sched_group_nodes[i] = sg;
  4974. for_each_cpu_mask(j, nodemask) {
  4975. struct sched_domain *sd;
  4976. sd = &per_cpu(node_domains, j);
  4977. sd->groups = sg;
  4978. if (sd->groups == NULL) {
  4979. /* Turn off balancing if we have no groups */
  4980. sd->flags = 0;
  4981. }
  4982. }
  4983. if (!sg) {
  4984. printk(KERN_WARNING
  4985. "Can not alloc domain group for node %d\n", i);
  4986. continue;
  4987. }
  4988. sg->cpu_power = 0;
  4989. sg->cpumask = nodemask;
  4990. cpus_or(covered, covered, nodemask);
  4991. prev = sg;
  4992. for (j = 0; j < MAX_NUMNODES; j++) {
  4993. cpumask_t tmp, notcovered;
  4994. int n = (i + j) % MAX_NUMNODES;
  4995. cpus_complement(notcovered, covered);
  4996. cpus_and(tmp, notcovered, *cpu_map);
  4997. cpus_and(tmp, tmp, domainspan);
  4998. if (cpus_empty(tmp))
  4999. break;
  5000. nodemask = node_to_cpumask(n);
  5001. cpus_and(tmp, tmp, nodemask);
  5002. if (cpus_empty(tmp))
  5003. continue;
  5004. sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
  5005. if (!sg) {
  5006. printk(KERN_WARNING
  5007. "Can not alloc domain group for node %d\n", j);
  5008. break;
  5009. }
  5010. sg->cpu_power = 0;
  5011. sg->cpumask = tmp;
  5012. cpus_or(covered, covered, tmp);
  5013. prev->next = sg;
  5014. prev = sg;
  5015. }
  5016. prev->next = sched_group_nodes[i];
  5017. }
  5018. #endif
  5019. /* Calculate CPU power for physical packages and nodes */
  5020. for_each_cpu_mask(i, *cpu_map) {
  5021. int power;
  5022. struct sched_domain *sd;
  5023. #ifdef CONFIG_SCHED_SMT
  5024. sd = &per_cpu(cpu_domains, i);
  5025. power = SCHED_LOAD_SCALE;
  5026. sd->groups->cpu_power = power;
  5027. #endif
  5028. sd = &per_cpu(phys_domains, i);
  5029. power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
  5030. (cpus_weight(sd->groups->cpumask)-1) / 10;
  5031. sd->groups->cpu_power = power;
  5032. #ifdef CONFIG_NUMA
  5033. sd = &per_cpu(allnodes_domains, i);
  5034. if (sd->groups) {
  5035. power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
  5036. (cpus_weight(sd->groups->cpumask)-1) / 10;
  5037. sd->groups->cpu_power = power;
  5038. }
  5039. #endif
  5040. }
  5041. #ifdef CONFIG_NUMA
  5042. for (i = 0; i < MAX_NUMNODES; i++) {
  5043. struct sched_group *sg = sched_group_nodes[i];
  5044. int j;
  5045. if (sg == NULL)
  5046. continue;
  5047. next_sg:
  5048. for_each_cpu_mask(j, sg->cpumask) {
  5049. struct sched_domain *sd;
  5050. int power;
  5051. sd = &per_cpu(phys_domains, j);
  5052. if (j != first_cpu(sd->groups->cpumask)) {
  5053. /*
  5054. * Only add "power" once for each
  5055. * physical package.
  5056. */
  5057. continue;
  5058. }
  5059. power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
  5060. (cpus_weight(sd->groups->cpumask)-1) / 10;
  5061. sg->cpu_power += power;
  5062. }
  5063. sg = sg->next;
  5064. if (sg != sched_group_nodes[i])
  5065. goto next_sg;
  5066. }
  5067. #endif
  5068. /* Attach the domains */
  5069. for_each_cpu_mask(i, *cpu_map) {
  5070. struct sched_domain *sd;
  5071. #ifdef CONFIG_SCHED_SMT
  5072. sd = &per_cpu(cpu_domains, i);
  5073. #else
  5074. sd = &per_cpu(phys_domains, i);
  5075. #endif
  5076. cpu_attach_domain(sd, i);
  5077. }
  5078. /*
  5079. * Tune cache-hot values:
  5080. */
  5081. calibrate_migration_costs(cpu_map);
  5082. }
  5083. /*
  5084. * Set up scheduler domains and groups. Callers must hold the hotplug lock.
  5085. */
  5086. static void arch_init_sched_domains(const cpumask_t *cpu_map)
  5087. {
  5088. cpumask_t cpu_default_map;
  5089. /*
  5090. * Setup mask for cpus without special case scheduling requirements.
  5091. * For now this just excludes isolated cpus, but could be used to
  5092. * exclude other special cases in the future.
  5093. */
  5094. cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
  5095. build_sched_domains(&cpu_default_map);
  5096. }
  5097. static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
  5098. {
  5099. #ifdef CONFIG_NUMA
  5100. int i;
  5101. int cpu;
  5102. for_each_cpu_mask(cpu, *cpu_map) {
  5103. struct sched_group *sched_group_allnodes
  5104. = sched_group_allnodes_bycpu[cpu];
  5105. struct sched_group **sched_group_nodes
  5106. = sched_group_nodes_bycpu[cpu];
  5107. if (sched_group_allnodes) {
  5108. kfree(sched_group_allnodes);
  5109. sched_group_allnodes_bycpu[cpu] = NULL;
  5110. }
  5111. if (!sched_group_nodes)
  5112. continue;
  5113. for (i = 0; i < MAX_NUMNODES; i++) {
  5114. cpumask_t nodemask = node_to_cpumask(i);
  5115. struct sched_group *oldsg, *sg = sched_group_nodes[i];
  5116. cpus_and(nodemask, nodemask, *cpu_map);
  5117. if (cpus_empty(nodemask))
  5118. continue;
  5119. if (sg == NULL)
  5120. continue;
  5121. sg = sg->next;
  5122. next_sg:
  5123. oldsg = sg;
  5124. sg = sg->next;
  5125. kfree(oldsg);
  5126. if (oldsg != sched_group_nodes[i])
  5127. goto next_sg;
  5128. }
  5129. kfree(sched_group_nodes);
  5130. sched_group_nodes_bycpu[cpu] = NULL;
  5131. }
  5132. #endif
  5133. }
  5134. /*
  5135. * Detach sched domains from a group of cpus specified in cpu_map
  5136. * These cpus will now be attached to the NULL domain
  5137. */
  5138. static void detach_destroy_domains(const cpumask_t *cpu_map)
  5139. {
  5140. int i;
  5141. for_each_cpu_mask(i, *cpu_map)
  5142. cpu_attach_domain(NULL, i);
  5143. synchronize_sched();
  5144. arch_destroy_sched_domains(cpu_map);
  5145. }
  5146. /*
  5147. * Partition sched domains as specified by the cpumasks below.
  5148. * This attaches all cpus from the cpumasks to the NULL domain,
  5149. * waits for a RCU quiescent period, recalculates sched
  5150. * domain information and then attaches them back to the
  5151. * correct sched domains
  5152. * Call with hotplug lock held
  5153. */
  5154. void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
  5155. {
  5156. cpumask_t change_map;
  5157. cpus_and(*partition1, *partition1, cpu_online_map);
  5158. cpus_and(*partition2, *partition2, cpu_online_map);
  5159. cpus_or(change_map, *partition1, *partition2);
  5160. /* Detach sched domains from all of the affected cpus */
  5161. detach_destroy_domains(&change_map);
  5162. if (!cpus_empty(*partition1))
  5163. build_sched_domains(partition1);
  5164. if (!cpus_empty(*partition2))
  5165. build_sched_domains(partition2);
  5166. }
  5167. #ifdef CONFIG_HOTPLUG_CPU
  5168. /*
  5169. * Force a reinitialization of the sched domains hierarchy. The domains
  5170. * and groups cannot be updated in place without racing with the balancing
  5171. * code, so we temporarily attach all running cpus to the NULL domain
  5172. * which will prevent rebalancing while the sched domains are recalculated.
  5173. */
  5174. static int update_sched_domains(struct notifier_block *nfb,
  5175. unsigned long action, void *hcpu)
  5176. {
  5177. switch (action) {
  5178. case CPU_UP_PREPARE:
  5179. case CPU_DOWN_PREPARE:
  5180. detach_destroy_domains(&cpu_online_map);
  5181. return NOTIFY_OK;
  5182. case CPU_UP_CANCELED:
  5183. case CPU_DOWN_FAILED:
  5184. case CPU_ONLINE:
  5185. case CPU_DEAD:
  5186. /*
  5187. * Fall through and re-initialise the domains.
  5188. */
  5189. break;
  5190. default:
  5191. return NOTIFY_DONE;
  5192. }
  5193. /* The hotplug lock is already held by cpu_up/cpu_down */
  5194. arch_init_sched_domains(&cpu_online_map);
  5195. return NOTIFY_OK;
  5196. }
  5197. #endif
  5198. void __init sched_init_smp(void)
  5199. {
  5200. lock_cpu_hotplug();
  5201. arch_init_sched_domains(&cpu_online_map);
  5202. unlock_cpu_hotplug();
  5203. /* XXX: Theoretical race here - CPU may be hotplugged now */
  5204. hotcpu_notifier(update_sched_domains, 0);
  5205. }
  5206. #else
  5207. void __init sched_init_smp(void)
  5208. {
  5209. }
  5210. #endif /* CONFIG_SMP */
  5211. int in_sched_functions(unsigned long addr)
  5212. {
  5213. /* Linker adds these: start and end of __sched functions */
  5214. extern char __sched_text_start[], __sched_text_end[];
  5215. return in_lock_functions(addr) ||
  5216. (addr >= (unsigned long)__sched_text_start
  5217. && addr < (unsigned long)__sched_text_end);
  5218. }
  5219. void __init sched_init(void)
  5220. {
  5221. runqueue_t *rq;
  5222. int i, j, k;
  5223. for_each_cpu(i) {
  5224. prio_array_t *array;
  5225. rq = cpu_rq(i);
  5226. spin_lock_init(&rq->lock);
  5227. rq->nr_running = 0;
  5228. rq->active = rq->arrays;
  5229. rq->expired = rq->arrays + 1;
  5230. rq->best_expired_prio = MAX_PRIO;
  5231. #ifdef CONFIG_SMP
  5232. rq->sd = NULL;
  5233. for (j = 1; j < 3; j++)
  5234. rq->cpu_load[j] = 0;
  5235. rq->active_balance = 0;
  5236. rq->push_cpu = 0;
  5237. rq->migration_thread = NULL;
  5238. INIT_LIST_HEAD(&rq->migration_queue);
  5239. #endif
  5240. atomic_set(&rq->nr_iowait, 0);
  5241. for (j = 0; j < 2; j++) {
  5242. array = rq->arrays + j;
  5243. for (k = 0; k < MAX_PRIO; k++) {
  5244. INIT_LIST_HEAD(array->queue + k);
  5245. __clear_bit(k, array->bitmap);
  5246. }
  5247. // delimiter for bitsearch
  5248. __set_bit(MAX_PRIO, array->bitmap);
  5249. }
  5250. }
  5251. /*
  5252. * The boot idle thread does lazy MMU switching as well:
  5253. */
  5254. atomic_inc(&init_mm.mm_count);
  5255. enter_lazy_tlb(&init_mm, current);
  5256. /*
  5257. * Make us the idle thread. Technically, schedule() should not be
  5258. * called from this thread, however somewhere below it might be,
  5259. * but because we are the idle thread, we just pick up running again
  5260. * when this runqueue becomes "idle".
  5261. */
  5262. init_idle(current, smp_processor_id());
  5263. }
  5264. #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
  5265. void __might_sleep(char *file, int line)
  5266. {
  5267. #if defined(in_atomic)
  5268. static unsigned long prev_jiffy; /* ratelimiting */
  5269. if ((in_atomic() || irqs_disabled()) &&
  5270. system_state == SYSTEM_RUNNING && !oops_in_progress) {
  5271. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  5272. return;
  5273. prev_jiffy = jiffies;
  5274. printk(KERN_ERR "Debug: sleeping function called from invalid"
  5275. " context at %s:%d\n", file, line);
  5276. printk("in_atomic():%d, irqs_disabled():%d\n",
  5277. in_atomic(), irqs_disabled());
  5278. dump_stack();
  5279. }
  5280. #endif
  5281. }
  5282. EXPORT_SYMBOL(__might_sleep);
  5283. #endif
  5284. #ifdef CONFIG_MAGIC_SYSRQ
  5285. void normalize_rt_tasks(void)
  5286. {
  5287. struct task_struct *p;
  5288. prio_array_t *array;
  5289. unsigned long flags;
  5290. runqueue_t *rq;
  5291. read_lock_irq(&tasklist_lock);
  5292. for_each_process (p) {
  5293. if (!rt_task(p))
  5294. continue;
  5295. rq = task_rq_lock(p, &flags);
  5296. array = p->array;
  5297. if (array)
  5298. deactivate_task(p, task_rq(p));
  5299. __setscheduler(p, SCHED_NORMAL, 0);
  5300. if (array) {
  5301. __activate_task(p, task_rq(p));
  5302. resched_task(rq->curr);
  5303. }
  5304. task_rq_unlock(rq, &flags);
  5305. }
  5306. read_unlock_irq(&tasklist_lock);
  5307. }
  5308. #endif /* CONFIG_MAGIC_SYSRQ */
  5309. #ifdef CONFIG_IA64
  5310. /*
  5311. * These functions are only useful for the IA64 MCA handling.
  5312. *
  5313. * They can only be called when the whole system has been
  5314. * stopped - every CPU needs to be quiescent, and no scheduling
  5315. * activity can take place. Using them for anything else would
  5316. * be a serious bug, and as a result, they aren't even visible
  5317. * under any other configuration.
  5318. */
  5319. /**
  5320. * curr_task - return the current task for a given cpu.
  5321. * @cpu: the processor in question.
  5322. *
  5323. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5324. */
  5325. task_t *curr_task(int cpu)
  5326. {
  5327. return cpu_curr(cpu);
  5328. }
  5329. /**
  5330. * set_curr_task - set the current task for a given cpu.
  5331. * @cpu: the processor in question.
  5332. * @p: the task pointer to set.
  5333. *
  5334. * Description: This function must only be used when non-maskable interrupts
  5335. * are serviced on a separate stack. It allows the architecture to switch the
  5336. * notion of the current task on a cpu in a non-blocking manner. This function
  5337. * must be called with all CPU's synchronized, and interrupts disabled, the
  5338. * and caller must save the original value of the current task (see
  5339. * curr_task() above) and restore that value before reenabling interrupts and
  5340. * re-starting the system.
  5341. *
  5342. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5343. */
  5344. void set_curr_task(int cpu, task_t *p)
  5345. {
  5346. cpu_curr(cpu) = p;
  5347. }
  5348. #endif