sched.c 177 KB

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