sched.c 137 KB

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