sched.c 164 KB

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