sched.c 154 KB

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