sched.c 153 KB

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