sched.c 154 KB

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