sched.c 170 KB

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