sched.c 174 KB

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