core.c 201 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422
  1. /*
  2. * kernel/sched/core.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. * 2007-04-15 Work begun on replacing all interactivity tuning with a
  20. * fair scheduling design by Con Kolivas.
  21. * 2007-05-05 Load balancing (smp-nice) and other improvements
  22. * by Peter Williams
  23. * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
  24. * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
  25. * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins,
  26. * Thomas Gleixner, Mike Kravetz
  27. */
  28. #include <linux/mm.h>
  29. #include <linux/module.h>
  30. #include <linux/nmi.h>
  31. #include <linux/init.h>
  32. #include <linux/uaccess.h>
  33. #include <linux/highmem.h>
  34. #include <asm/mmu_context.h>
  35. #include <linux/interrupt.h>
  36. #include <linux/capability.h>
  37. #include <linux/completion.h>
  38. #include <linux/kernel_stat.h>
  39. #include <linux/debug_locks.h>
  40. #include <linux/perf_event.h>
  41. #include <linux/security.h>
  42. #include <linux/notifier.h>
  43. #include <linux/profile.h>
  44. #include <linux/freezer.h>
  45. #include <linux/vmalloc.h>
  46. #include <linux/blkdev.h>
  47. #include <linux/delay.h>
  48. #include <linux/pid_namespace.h>
  49. #include <linux/smp.h>
  50. #include <linux/threads.h>
  51. #include <linux/timer.h>
  52. #include <linux/rcupdate.h>
  53. #include <linux/cpu.h>
  54. #include <linux/cpuset.h>
  55. #include <linux/percpu.h>
  56. #include <linux/proc_fs.h>
  57. #include <linux/seq_file.h>
  58. #include <linux/sysctl.h>
  59. #include <linux/syscalls.h>
  60. #include <linux/times.h>
  61. #include <linux/tsacct_kern.h>
  62. #include <linux/kprobes.h>
  63. #include <linux/delayacct.h>
  64. #include <linux/unistd.h>
  65. #include <linux/pagemap.h>
  66. #include <linux/hrtimer.h>
  67. #include <linux/tick.h>
  68. #include <linux/debugfs.h>
  69. #include <linux/ctype.h>
  70. #include <linux/ftrace.h>
  71. #include <linux/slab.h>
  72. #include <linux/init_task.h>
  73. #include <linux/binfmts.h>
  74. #include <linux/context_tracking.h>
  75. #include <linux/compiler.h>
  76. #include <asm/switch_to.h>
  77. #include <asm/tlb.h>
  78. #include <asm/irq_regs.h>
  79. #include <asm/mutex.h>
  80. #ifdef CONFIG_PARAVIRT
  81. #include <asm/paravirt.h>
  82. #endif
  83. #include "sched.h"
  84. #include "../workqueue_internal.h"
  85. #include "../smpboot.h"
  86. #define CREATE_TRACE_POINTS
  87. #include <trace/events/sched.h>
  88. void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period)
  89. {
  90. unsigned long delta;
  91. ktime_t soft, hard, now;
  92. for (;;) {
  93. if (hrtimer_active(period_timer))
  94. break;
  95. now = hrtimer_cb_get_time(period_timer);
  96. hrtimer_forward(period_timer, now, period);
  97. soft = hrtimer_get_softexpires(period_timer);
  98. hard = hrtimer_get_expires(period_timer);
  99. delta = ktime_to_ns(ktime_sub(hard, soft));
  100. __hrtimer_start_range_ns(period_timer, soft, delta,
  101. HRTIMER_MODE_ABS_PINNED, 0);
  102. }
  103. }
  104. DEFINE_MUTEX(sched_domains_mutex);
  105. DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
  106. static void update_rq_clock_task(struct rq *rq, s64 delta);
  107. void update_rq_clock(struct rq *rq)
  108. {
  109. s64 delta;
  110. lockdep_assert_held(&rq->lock);
  111. if (rq->clock_skip_update & RQCF_ACT_SKIP)
  112. return;
  113. delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
  114. if (delta < 0)
  115. return;
  116. rq->clock += delta;
  117. update_rq_clock_task(rq, delta);
  118. }
  119. /*
  120. * Debugging: various feature bits
  121. */
  122. #define SCHED_FEAT(name, enabled) \
  123. (1UL << __SCHED_FEAT_##name) * enabled |
  124. const_debug unsigned int sysctl_sched_features =
  125. #include "features.h"
  126. 0;
  127. #undef SCHED_FEAT
  128. #ifdef CONFIG_SCHED_DEBUG
  129. #define SCHED_FEAT(name, enabled) \
  130. #name ,
  131. static const char * const sched_feat_names[] = {
  132. #include "features.h"
  133. };
  134. #undef SCHED_FEAT
  135. static int sched_feat_show(struct seq_file *m, void *v)
  136. {
  137. int i;
  138. for (i = 0; i < __SCHED_FEAT_NR; i++) {
  139. if (!(sysctl_sched_features & (1UL << i)))
  140. seq_puts(m, "NO_");
  141. seq_printf(m, "%s ", sched_feat_names[i]);
  142. }
  143. seq_puts(m, "\n");
  144. return 0;
  145. }
  146. #ifdef HAVE_JUMP_LABEL
  147. #define jump_label_key__true STATIC_KEY_INIT_TRUE
  148. #define jump_label_key__false STATIC_KEY_INIT_FALSE
  149. #define SCHED_FEAT(name, enabled) \
  150. jump_label_key__##enabled ,
  151. struct static_key sched_feat_keys[__SCHED_FEAT_NR] = {
  152. #include "features.h"
  153. };
  154. #undef SCHED_FEAT
  155. static void sched_feat_disable(int i)
  156. {
  157. if (static_key_enabled(&sched_feat_keys[i]))
  158. static_key_slow_dec(&sched_feat_keys[i]);
  159. }
  160. static void sched_feat_enable(int i)
  161. {
  162. if (!static_key_enabled(&sched_feat_keys[i]))
  163. static_key_slow_inc(&sched_feat_keys[i]);
  164. }
  165. #else
  166. static void sched_feat_disable(int i) { };
  167. static void sched_feat_enable(int i) { };
  168. #endif /* HAVE_JUMP_LABEL */
  169. static int sched_feat_set(char *cmp)
  170. {
  171. int i;
  172. int neg = 0;
  173. if (strncmp(cmp, "NO_", 3) == 0) {
  174. neg = 1;
  175. cmp += 3;
  176. }
  177. for (i = 0; i < __SCHED_FEAT_NR; i++) {
  178. if (strcmp(cmp, sched_feat_names[i]) == 0) {
  179. if (neg) {
  180. sysctl_sched_features &= ~(1UL << i);
  181. sched_feat_disable(i);
  182. } else {
  183. sysctl_sched_features |= (1UL << i);
  184. sched_feat_enable(i);
  185. }
  186. break;
  187. }
  188. }
  189. return i;
  190. }
  191. static ssize_t
  192. sched_feat_write(struct file *filp, const char __user *ubuf,
  193. size_t cnt, loff_t *ppos)
  194. {
  195. char buf[64];
  196. char *cmp;
  197. int i;
  198. struct inode *inode;
  199. if (cnt > 63)
  200. cnt = 63;
  201. if (copy_from_user(&buf, ubuf, cnt))
  202. return -EFAULT;
  203. buf[cnt] = 0;
  204. cmp = strstrip(buf);
  205. /* Ensure the static_key remains in a consistent state */
  206. inode = file_inode(filp);
  207. mutex_lock(&inode->i_mutex);
  208. i = sched_feat_set(cmp);
  209. mutex_unlock(&inode->i_mutex);
  210. if (i == __SCHED_FEAT_NR)
  211. return -EINVAL;
  212. *ppos += cnt;
  213. return cnt;
  214. }
  215. static int sched_feat_open(struct inode *inode, struct file *filp)
  216. {
  217. return single_open(filp, sched_feat_show, NULL);
  218. }
  219. static const struct file_operations sched_feat_fops = {
  220. .open = sched_feat_open,
  221. .write = sched_feat_write,
  222. .read = seq_read,
  223. .llseek = seq_lseek,
  224. .release = single_release,
  225. };
  226. static __init int sched_init_debug(void)
  227. {
  228. debugfs_create_file("sched_features", 0644, NULL, NULL,
  229. &sched_feat_fops);
  230. return 0;
  231. }
  232. late_initcall(sched_init_debug);
  233. #endif /* CONFIG_SCHED_DEBUG */
  234. /*
  235. * Number of tasks to iterate in a single balance run.
  236. * Limited because this is done with IRQs disabled.
  237. */
  238. const_debug unsigned int sysctl_sched_nr_migrate = 32;
  239. /*
  240. * period over which we average the RT time consumption, measured
  241. * in ms.
  242. *
  243. * default: 1s
  244. */
  245. const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
  246. /*
  247. * period over which we measure -rt task cpu usage in us.
  248. * default: 1s
  249. */
  250. unsigned int sysctl_sched_rt_period = 1000000;
  251. __read_mostly int scheduler_running;
  252. /*
  253. * part of the period that we allow rt tasks to run in us.
  254. * default: 0.95s
  255. */
  256. int sysctl_sched_rt_runtime = 950000;
  257. /* cpus with isolated domains */
  258. cpumask_var_t cpu_isolated_map;
  259. /*
  260. * this_rq_lock - lock this runqueue and disable interrupts.
  261. */
  262. static struct rq *this_rq_lock(void)
  263. __acquires(rq->lock)
  264. {
  265. struct rq *rq;
  266. local_irq_disable();
  267. rq = this_rq();
  268. raw_spin_lock(&rq->lock);
  269. return rq;
  270. }
  271. #ifdef CONFIG_SCHED_HRTICK
  272. /*
  273. * Use HR-timers to deliver accurate preemption points.
  274. */
  275. static void hrtick_clear(struct rq *rq)
  276. {
  277. if (hrtimer_active(&rq->hrtick_timer))
  278. hrtimer_cancel(&rq->hrtick_timer);
  279. }
  280. /*
  281. * High-resolution timer tick.
  282. * Runs from hardirq context with interrupts disabled.
  283. */
  284. static enum hrtimer_restart hrtick(struct hrtimer *timer)
  285. {
  286. struct rq *rq = container_of(timer, struct rq, hrtick_timer);
  287. WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
  288. raw_spin_lock(&rq->lock);
  289. update_rq_clock(rq);
  290. rq->curr->sched_class->task_tick(rq, rq->curr, 1);
  291. raw_spin_unlock(&rq->lock);
  292. return HRTIMER_NORESTART;
  293. }
  294. #ifdef CONFIG_SMP
  295. static int __hrtick_restart(struct rq *rq)
  296. {
  297. struct hrtimer *timer = &rq->hrtick_timer;
  298. ktime_t time = hrtimer_get_softexpires(timer);
  299. return __hrtimer_start_range_ns(timer, time, 0, HRTIMER_MODE_ABS_PINNED, 0);
  300. }
  301. /*
  302. * called from hardirq (IPI) context
  303. */
  304. static void __hrtick_start(void *arg)
  305. {
  306. struct rq *rq = arg;
  307. raw_spin_lock(&rq->lock);
  308. __hrtick_restart(rq);
  309. rq->hrtick_csd_pending = 0;
  310. raw_spin_unlock(&rq->lock);
  311. }
  312. /*
  313. * Called to set the hrtick timer state.
  314. *
  315. * called with rq->lock held and irqs disabled
  316. */
  317. void hrtick_start(struct rq *rq, u64 delay)
  318. {
  319. struct hrtimer *timer = &rq->hrtick_timer;
  320. ktime_t time;
  321. s64 delta;
  322. /*
  323. * Don't schedule slices shorter than 10000ns, that just
  324. * doesn't make sense and can cause timer DoS.
  325. */
  326. delta = max_t(s64, delay, 10000LL);
  327. time = ktime_add_ns(timer->base->get_time(), delta);
  328. hrtimer_set_expires(timer, time);
  329. if (rq == this_rq()) {
  330. __hrtick_restart(rq);
  331. } else if (!rq->hrtick_csd_pending) {
  332. smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
  333. rq->hrtick_csd_pending = 1;
  334. }
  335. }
  336. static int
  337. hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
  338. {
  339. int cpu = (int)(long)hcpu;
  340. switch (action) {
  341. case CPU_UP_CANCELED:
  342. case CPU_UP_CANCELED_FROZEN:
  343. case CPU_DOWN_PREPARE:
  344. case CPU_DOWN_PREPARE_FROZEN:
  345. case CPU_DEAD:
  346. case CPU_DEAD_FROZEN:
  347. hrtick_clear(cpu_rq(cpu));
  348. return NOTIFY_OK;
  349. }
  350. return NOTIFY_DONE;
  351. }
  352. static __init void init_hrtick(void)
  353. {
  354. hotcpu_notifier(hotplug_hrtick, 0);
  355. }
  356. #else
  357. /*
  358. * Called to set the hrtick timer state.
  359. *
  360. * called with rq->lock held and irqs disabled
  361. */
  362. void hrtick_start(struct rq *rq, u64 delay)
  363. {
  364. /*
  365. * Don't schedule slices shorter than 10000ns, that just
  366. * doesn't make sense. Rely on vruntime for fairness.
  367. */
  368. delay = max_t(u64, delay, 10000LL);
  369. __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
  370. HRTIMER_MODE_REL_PINNED, 0);
  371. }
  372. static inline void init_hrtick(void)
  373. {
  374. }
  375. #endif /* CONFIG_SMP */
  376. static void init_rq_hrtick(struct rq *rq)
  377. {
  378. #ifdef CONFIG_SMP
  379. rq->hrtick_csd_pending = 0;
  380. rq->hrtick_csd.flags = 0;
  381. rq->hrtick_csd.func = __hrtick_start;
  382. rq->hrtick_csd.info = rq;
  383. #endif
  384. hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  385. rq->hrtick_timer.function = hrtick;
  386. }
  387. #else /* CONFIG_SCHED_HRTICK */
  388. static inline void hrtick_clear(struct rq *rq)
  389. {
  390. }
  391. static inline void init_rq_hrtick(struct rq *rq)
  392. {
  393. }
  394. static inline void init_hrtick(void)
  395. {
  396. }
  397. #endif /* CONFIG_SCHED_HRTICK */
  398. /*
  399. * cmpxchg based fetch_or, macro so it works for different integer types
  400. */
  401. #define fetch_or(ptr, val) \
  402. ({ typeof(*(ptr)) __old, __val = *(ptr); \
  403. for (;;) { \
  404. __old = cmpxchg((ptr), __val, __val | (val)); \
  405. if (__old == __val) \
  406. break; \
  407. __val = __old; \
  408. } \
  409. __old; \
  410. })
  411. #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
  412. /*
  413. * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
  414. * this avoids any races wrt polling state changes and thereby avoids
  415. * spurious IPIs.
  416. */
  417. static bool set_nr_and_not_polling(struct task_struct *p)
  418. {
  419. struct thread_info *ti = task_thread_info(p);
  420. return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
  421. }
  422. /*
  423. * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
  424. *
  425. * If this returns true, then the idle task promises to call
  426. * sched_ttwu_pending() and reschedule soon.
  427. */
  428. static bool set_nr_if_polling(struct task_struct *p)
  429. {
  430. struct thread_info *ti = task_thread_info(p);
  431. typeof(ti->flags) old, val = READ_ONCE(ti->flags);
  432. for (;;) {
  433. if (!(val & _TIF_POLLING_NRFLAG))
  434. return false;
  435. if (val & _TIF_NEED_RESCHED)
  436. return true;
  437. old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
  438. if (old == val)
  439. break;
  440. val = old;
  441. }
  442. return true;
  443. }
  444. #else
  445. static bool set_nr_and_not_polling(struct task_struct *p)
  446. {
  447. set_tsk_need_resched(p);
  448. return true;
  449. }
  450. #ifdef CONFIG_SMP
  451. static bool set_nr_if_polling(struct task_struct *p)
  452. {
  453. return false;
  454. }
  455. #endif
  456. #endif
  457. void wake_q_add(struct wake_q_head *head, struct task_struct *task)
  458. {
  459. struct wake_q_node *node = &task->wake_q;
  460. /*
  461. * Atomically grab the task, if ->wake_q is !nil already it means
  462. * its already queued (either by us or someone else) and will get the
  463. * wakeup due to that.
  464. *
  465. * This cmpxchg() implies a full barrier, which pairs with the write
  466. * barrier implied by the wakeup in wake_up_list().
  467. */
  468. if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
  469. return;
  470. get_task_struct(task);
  471. /*
  472. * The head is context local, there can be no concurrency.
  473. */
  474. *head->lastp = node;
  475. head->lastp = &node->next;
  476. }
  477. void wake_up_q(struct wake_q_head *head)
  478. {
  479. struct wake_q_node *node = head->first;
  480. while (node != WAKE_Q_TAIL) {
  481. struct task_struct *task;
  482. task = container_of(node, struct task_struct, wake_q);
  483. BUG_ON(!task);
  484. /* task can safely be re-inserted now */
  485. node = node->next;
  486. task->wake_q.next = NULL;
  487. /*
  488. * wake_up_process() implies a wmb() to pair with the queueing
  489. * in wake_q_add() so as not to miss wakeups.
  490. */
  491. wake_up_process(task);
  492. put_task_struct(task);
  493. }
  494. }
  495. /*
  496. * resched_curr - mark rq's current task 'to be rescheduled now'.
  497. *
  498. * On UP this means the setting of the need_resched flag, on SMP it
  499. * might also involve a cross-CPU call to trigger the scheduler on
  500. * the target CPU.
  501. */
  502. void resched_curr(struct rq *rq)
  503. {
  504. struct task_struct *curr = rq->curr;
  505. int cpu;
  506. lockdep_assert_held(&rq->lock);
  507. if (test_tsk_need_resched(curr))
  508. return;
  509. cpu = cpu_of(rq);
  510. if (cpu == smp_processor_id()) {
  511. set_tsk_need_resched(curr);
  512. set_preempt_need_resched();
  513. return;
  514. }
  515. if (set_nr_and_not_polling(curr))
  516. smp_send_reschedule(cpu);
  517. else
  518. trace_sched_wake_idle_without_ipi(cpu);
  519. }
  520. void resched_cpu(int cpu)
  521. {
  522. struct rq *rq = cpu_rq(cpu);
  523. unsigned long flags;
  524. if (!raw_spin_trylock_irqsave(&rq->lock, flags))
  525. return;
  526. resched_curr(rq);
  527. raw_spin_unlock_irqrestore(&rq->lock, flags);
  528. }
  529. #ifdef CONFIG_SMP
  530. #ifdef CONFIG_NO_HZ_COMMON
  531. /*
  532. * In the semi idle case, use the nearest busy cpu for migrating timers
  533. * from an idle cpu. This is good for power-savings.
  534. *
  535. * We don't do similar optimization for completely idle system, as
  536. * selecting an idle cpu will add more delays to the timers than intended
  537. * (as that cpu's timer base may not be uptodate wrt jiffies etc).
  538. */
  539. int get_nohz_timer_target(int pinned)
  540. {
  541. int cpu = smp_processor_id();
  542. int i;
  543. struct sched_domain *sd;
  544. if (pinned || !get_sysctl_timer_migration() || !idle_cpu(cpu))
  545. return cpu;
  546. rcu_read_lock();
  547. for_each_domain(cpu, sd) {
  548. for_each_cpu(i, sched_domain_span(sd)) {
  549. if (!idle_cpu(i)) {
  550. cpu = i;
  551. goto unlock;
  552. }
  553. }
  554. }
  555. unlock:
  556. rcu_read_unlock();
  557. return cpu;
  558. }
  559. /*
  560. * When add_timer_on() enqueues a timer into the timer wheel of an
  561. * idle CPU then this timer might expire before the next timer event
  562. * which is scheduled to wake up that CPU. In case of a completely
  563. * idle system the next event might even be infinite time into the
  564. * future. wake_up_idle_cpu() ensures that the CPU is woken up and
  565. * leaves the inner idle loop so the newly added timer is taken into
  566. * account when the CPU goes back to idle and evaluates the timer
  567. * wheel for the next timer event.
  568. */
  569. static void wake_up_idle_cpu(int cpu)
  570. {
  571. struct rq *rq = cpu_rq(cpu);
  572. if (cpu == smp_processor_id())
  573. return;
  574. if (set_nr_and_not_polling(rq->idle))
  575. smp_send_reschedule(cpu);
  576. else
  577. trace_sched_wake_idle_without_ipi(cpu);
  578. }
  579. static bool wake_up_full_nohz_cpu(int cpu)
  580. {
  581. /*
  582. * We just need the target to call irq_exit() and re-evaluate
  583. * the next tick. The nohz full kick at least implies that.
  584. * If needed we can still optimize that later with an
  585. * empty IRQ.
  586. */
  587. if (tick_nohz_full_cpu(cpu)) {
  588. if (cpu != smp_processor_id() ||
  589. tick_nohz_tick_stopped())
  590. tick_nohz_full_kick_cpu(cpu);
  591. return true;
  592. }
  593. return false;
  594. }
  595. void wake_up_nohz_cpu(int cpu)
  596. {
  597. if (!wake_up_full_nohz_cpu(cpu))
  598. wake_up_idle_cpu(cpu);
  599. }
  600. static inline bool got_nohz_idle_kick(void)
  601. {
  602. int cpu = smp_processor_id();
  603. if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
  604. return false;
  605. if (idle_cpu(cpu) && !need_resched())
  606. return true;
  607. /*
  608. * We can't run Idle Load Balance on this CPU for this time so we
  609. * cancel it and clear NOHZ_BALANCE_KICK
  610. */
  611. clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
  612. return false;
  613. }
  614. #else /* CONFIG_NO_HZ_COMMON */
  615. static inline bool got_nohz_idle_kick(void)
  616. {
  617. return false;
  618. }
  619. #endif /* CONFIG_NO_HZ_COMMON */
  620. #ifdef CONFIG_NO_HZ_FULL
  621. bool sched_can_stop_tick(void)
  622. {
  623. /*
  624. * FIFO realtime policy runs the highest priority task. Other runnable
  625. * tasks are of a lower priority. The scheduler tick does nothing.
  626. */
  627. if (current->policy == SCHED_FIFO)
  628. return true;
  629. /*
  630. * Round-robin realtime tasks time slice with other tasks at the same
  631. * realtime priority. Is this task the only one at this priority?
  632. */
  633. if (current->policy == SCHED_RR) {
  634. struct sched_rt_entity *rt_se = &current->rt;
  635. return rt_se->run_list.prev == rt_se->run_list.next;
  636. }
  637. /*
  638. * More than one running task need preemption.
  639. * nr_running update is assumed to be visible
  640. * after IPI is sent from wakers.
  641. */
  642. if (this_rq()->nr_running > 1)
  643. return false;
  644. return true;
  645. }
  646. #endif /* CONFIG_NO_HZ_FULL */
  647. void sched_avg_update(struct rq *rq)
  648. {
  649. s64 period = sched_avg_period();
  650. while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
  651. /*
  652. * Inline assembly required to prevent the compiler
  653. * optimising this loop into a divmod call.
  654. * See __iter_div_u64_rem() for another example of this.
  655. */
  656. asm("" : "+rm" (rq->age_stamp));
  657. rq->age_stamp += period;
  658. rq->rt_avg /= 2;
  659. }
  660. }
  661. #endif /* CONFIG_SMP */
  662. #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
  663. (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
  664. /*
  665. * Iterate task_group tree rooted at *from, calling @down when first entering a
  666. * node and @up when leaving it for the final time.
  667. *
  668. * Caller must hold rcu_lock or sufficient equivalent.
  669. */
  670. int walk_tg_tree_from(struct task_group *from,
  671. tg_visitor down, tg_visitor up, void *data)
  672. {
  673. struct task_group *parent, *child;
  674. int ret;
  675. parent = from;
  676. down:
  677. ret = (*down)(parent, data);
  678. if (ret)
  679. goto out;
  680. list_for_each_entry_rcu(child, &parent->children, siblings) {
  681. parent = child;
  682. goto down;
  683. up:
  684. continue;
  685. }
  686. ret = (*up)(parent, data);
  687. if (ret || parent == from)
  688. goto out;
  689. child = parent;
  690. parent = parent->parent;
  691. if (parent)
  692. goto up;
  693. out:
  694. return ret;
  695. }
  696. int tg_nop(struct task_group *tg, void *data)
  697. {
  698. return 0;
  699. }
  700. #endif
  701. static void set_load_weight(struct task_struct *p)
  702. {
  703. int prio = p->static_prio - MAX_RT_PRIO;
  704. struct load_weight *load = &p->se.load;
  705. /*
  706. * SCHED_IDLE tasks get minimal weight:
  707. */
  708. if (p->policy == SCHED_IDLE) {
  709. load->weight = scale_load(WEIGHT_IDLEPRIO);
  710. load->inv_weight = WMULT_IDLEPRIO;
  711. return;
  712. }
  713. load->weight = scale_load(prio_to_weight[prio]);
  714. load->inv_weight = prio_to_wmult[prio];
  715. }
  716. static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
  717. {
  718. update_rq_clock(rq);
  719. sched_info_queued(rq, p);
  720. p->sched_class->enqueue_task(rq, p, flags);
  721. }
  722. static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  723. {
  724. update_rq_clock(rq);
  725. sched_info_dequeued(rq, p);
  726. p->sched_class->dequeue_task(rq, p, flags);
  727. }
  728. void activate_task(struct rq *rq, struct task_struct *p, int flags)
  729. {
  730. if (task_contributes_to_load(p))
  731. rq->nr_uninterruptible--;
  732. enqueue_task(rq, p, flags);
  733. }
  734. void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
  735. {
  736. if (task_contributes_to_load(p))
  737. rq->nr_uninterruptible++;
  738. dequeue_task(rq, p, flags);
  739. }
  740. static void update_rq_clock_task(struct rq *rq, s64 delta)
  741. {
  742. /*
  743. * In theory, the compile should just see 0 here, and optimize out the call
  744. * to sched_rt_avg_update. But I don't trust it...
  745. */
  746. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  747. s64 steal = 0, irq_delta = 0;
  748. #endif
  749. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  750. irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
  751. /*
  752. * Since irq_time is only updated on {soft,}irq_exit, we might run into
  753. * this case when a previous update_rq_clock() happened inside a
  754. * {soft,}irq region.
  755. *
  756. * When this happens, we stop ->clock_task and only update the
  757. * prev_irq_time stamp to account for the part that fit, so that a next
  758. * update will consume the rest. This ensures ->clock_task is
  759. * monotonic.
  760. *
  761. * It does however cause some slight miss-attribution of {soft,}irq
  762. * time, a more accurate solution would be to update the irq_time using
  763. * the current rq->clock timestamp, except that would require using
  764. * atomic ops.
  765. */
  766. if (irq_delta > delta)
  767. irq_delta = delta;
  768. rq->prev_irq_time += irq_delta;
  769. delta -= irq_delta;
  770. #endif
  771. #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
  772. if (static_key_false((&paravirt_steal_rq_enabled))) {
  773. steal = paravirt_steal_clock(cpu_of(rq));
  774. steal -= rq->prev_steal_time_rq;
  775. if (unlikely(steal > delta))
  776. steal = delta;
  777. rq->prev_steal_time_rq += steal;
  778. delta -= steal;
  779. }
  780. #endif
  781. rq->clock_task += delta;
  782. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  783. if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
  784. sched_rt_avg_update(rq, irq_delta + steal);
  785. #endif
  786. }
  787. void sched_set_stop_task(int cpu, struct task_struct *stop)
  788. {
  789. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  790. struct task_struct *old_stop = cpu_rq(cpu)->stop;
  791. if (stop) {
  792. /*
  793. * Make it appear like a SCHED_FIFO task, its something
  794. * userspace knows about and won't get confused about.
  795. *
  796. * Also, it will make PI more or less work without too
  797. * much confusion -- but then, stop work should not
  798. * rely on PI working anyway.
  799. */
  800. sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
  801. stop->sched_class = &stop_sched_class;
  802. }
  803. cpu_rq(cpu)->stop = stop;
  804. if (old_stop) {
  805. /*
  806. * Reset it back to a normal scheduling class so that
  807. * it can die in pieces.
  808. */
  809. old_stop->sched_class = &rt_sched_class;
  810. }
  811. }
  812. /*
  813. * __normal_prio - return the priority that is based on the static prio
  814. */
  815. static inline int __normal_prio(struct task_struct *p)
  816. {
  817. return p->static_prio;
  818. }
  819. /*
  820. * Calculate the expected normal priority: i.e. priority
  821. * without taking RT-inheritance into account. Might be
  822. * boosted by interactivity modifiers. Changes upon fork,
  823. * setprio syscalls, and whenever the interactivity
  824. * estimator recalculates.
  825. */
  826. static inline int normal_prio(struct task_struct *p)
  827. {
  828. int prio;
  829. if (task_has_dl_policy(p))
  830. prio = MAX_DL_PRIO-1;
  831. else if (task_has_rt_policy(p))
  832. prio = MAX_RT_PRIO-1 - p->rt_priority;
  833. else
  834. prio = __normal_prio(p);
  835. return prio;
  836. }
  837. /*
  838. * Calculate the current priority, i.e. the priority
  839. * taken into account by the scheduler. This value might
  840. * be boosted by RT tasks, or might be boosted by
  841. * interactivity modifiers. Will be RT if the task got
  842. * RT-boosted. If not then it returns p->normal_prio.
  843. */
  844. static int effective_prio(struct task_struct *p)
  845. {
  846. p->normal_prio = normal_prio(p);
  847. /*
  848. * If we are RT tasks or we were boosted to RT priority,
  849. * keep the priority unchanged. Otherwise, update priority
  850. * to the normal priority:
  851. */
  852. if (!rt_prio(p->prio))
  853. return p->normal_prio;
  854. return p->prio;
  855. }
  856. /**
  857. * task_curr - is this task currently executing on a CPU?
  858. * @p: the task in question.
  859. *
  860. * Return: 1 if the task is currently executing. 0 otherwise.
  861. */
  862. inline int task_curr(const struct task_struct *p)
  863. {
  864. return cpu_curr(task_cpu(p)) == p;
  865. }
  866. /*
  867. * Can drop rq->lock because from sched_class::switched_from() methods drop it.
  868. */
  869. static inline void check_class_changed(struct rq *rq, struct task_struct *p,
  870. const struct sched_class *prev_class,
  871. int oldprio)
  872. {
  873. if (prev_class != p->sched_class) {
  874. if (prev_class->switched_from)
  875. prev_class->switched_from(rq, p);
  876. /* Possble rq->lock 'hole'. */
  877. p->sched_class->switched_to(rq, p);
  878. } else if (oldprio != p->prio || dl_task(p))
  879. p->sched_class->prio_changed(rq, p, oldprio);
  880. }
  881. void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
  882. {
  883. const struct sched_class *class;
  884. if (p->sched_class == rq->curr->sched_class) {
  885. rq->curr->sched_class->check_preempt_curr(rq, p, flags);
  886. } else {
  887. for_each_class(class) {
  888. if (class == rq->curr->sched_class)
  889. break;
  890. if (class == p->sched_class) {
  891. resched_curr(rq);
  892. break;
  893. }
  894. }
  895. }
  896. /*
  897. * A queue event has occurred, and we're going to schedule. In
  898. * this case, we can save a useless back to back clock update.
  899. */
  900. if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
  901. rq_clock_skip_update(rq, true);
  902. }
  903. #ifdef CONFIG_SMP
  904. void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
  905. {
  906. #ifdef CONFIG_SCHED_DEBUG
  907. /*
  908. * We should never call set_task_cpu() on a blocked task,
  909. * ttwu() will sort out the placement.
  910. */
  911. WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
  912. !p->on_rq);
  913. #ifdef CONFIG_LOCKDEP
  914. /*
  915. * The caller should hold either p->pi_lock or rq->lock, when changing
  916. * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
  917. *
  918. * sched_move_task() holds both and thus holding either pins the cgroup,
  919. * see task_group().
  920. *
  921. * Furthermore, all task_rq users should acquire both locks, see
  922. * task_rq_lock().
  923. */
  924. WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
  925. lockdep_is_held(&task_rq(p)->lock)));
  926. #endif
  927. #endif
  928. trace_sched_migrate_task(p, new_cpu);
  929. if (task_cpu(p) != new_cpu) {
  930. if (p->sched_class->migrate_task_rq)
  931. p->sched_class->migrate_task_rq(p, new_cpu);
  932. p->se.nr_migrations++;
  933. perf_sw_event_sched(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 0);
  934. }
  935. __set_task_cpu(p, new_cpu);
  936. }
  937. static void __migrate_swap_task(struct task_struct *p, int cpu)
  938. {
  939. if (task_on_rq_queued(p)) {
  940. struct rq *src_rq, *dst_rq;
  941. src_rq = task_rq(p);
  942. dst_rq = cpu_rq(cpu);
  943. deactivate_task(src_rq, p, 0);
  944. set_task_cpu(p, cpu);
  945. activate_task(dst_rq, p, 0);
  946. check_preempt_curr(dst_rq, p, 0);
  947. } else {
  948. /*
  949. * Task isn't running anymore; make it appear like we migrated
  950. * it before it went to sleep. This means on wakeup we make the
  951. * previous cpu our targer instead of where it really is.
  952. */
  953. p->wake_cpu = cpu;
  954. }
  955. }
  956. struct migration_swap_arg {
  957. struct task_struct *src_task, *dst_task;
  958. int src_cpu, dst_cpu;
  959. };
  960. static int migrate_swap_stop(void *data)
  961. {
  962. struct migration_swap_arg *arg = data;
  963. struct rq *src_rq, *dst_rq;
  964. int ret = -EAGAIN;
  965. src_rq = cpu_rq(arg->src_cpu);
  966. dst_rq = cpu_rq(arg->dst_cpu);
  967. double_raw_lock(&arg->src_task->pi_lock,
  968. &arg->dst_task->pi_lock);
  969. double_rq_lock(src_rq, dst_rq);
  970. if (task_cpu(arg->dst_task) != arg->dst_cpu)
  971. goto unlock;
  972. if (task_cpu(arg->src_task) != arg->src_cpu)
  973. goto unlock;
  974. if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task)))
  975. goto unlock;
  976. if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task)))
  977. goto unlock;
  978. __migrate_swap_task(arg->src_task, arg->dst_cpu);
  979. __migrate_swap_task(arg->dst_task, arg->src_cpu);
  980. ret = 0;
  981. unlock:
  982. double_rq_unlock(src_rq, dst_rq);
  983. raw_spin_unlock(&arg->dst_task->pi_lock);
  984. raw_spin_unlock(&arg->src_task->pi_lock);
  985. return ret;
  986. }
  987. /*
  988. * Cross migrate two tasks
  989. */
  990. int migrate_swap(struct task_struct *cur, struct task_struct *p)
  991. {
  992. struct migration_swap_arg arg;
  993. int ret = -EINVAL;
  994. arg = (struct migration_swap_arg){
  995. .src_task = cur,
  996. .src_cpu = task_cpu(cur),
  997. .dst_task = p,
  998. .dst_cpu = task_cpu(p),
  999. };
  1000. if (arg.src_cpu == arg.dst_cpu)
  1001. goto out;
  1002. /*
  1003. * These three tests are all lockless; this is OK since all of them
  1004. * will be re-checked with proper locks held further down the line.
  1005. */
  1006. if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
  1007. goto out;
  1008. if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task)))
  1009. goto out;
  1010. if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task)))
  1011. goto out;
  1012. trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
  1013. ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
  1014. out:
  1015. return ret;
  1016. }
  1017. struct migration_arg {
  1018. struct task_struct *task;
  1019. int dest_cpu;
  1020. };
  1021. static int migration_cpu_stop(void *data);
  1022. /*
  1023. * wait_task_inactive - wait for a thread to unschedule.
  1024. *
  1025. * If @match_state is nonzero, it's the @p->state value just checked and
  1026. * not expected to change. If it changes, i.e. @p might have woken up,
  1027. * then return zero. When we succeed in waiting for @p to be off its CPU,
  1028. * we return a positive number (its total switch count). If a second call
  1029. * a short while later returns the same number, the caller can be sure that
  1030. * @p has remained unscheduled the whole time.
  1031. *
  1032. * The caller must ensure that the task *will* unschedule sometime soon,
  1033. * else this function might spin for a *long* time. This function can't
  1034. * be called with interrupts off, or it may introduce deadlock with
  1035. * smp_call_function() if an IPI is sent by the same process we are
  1036. * waiting to become inactive.
  1037. */
  1038. unsigned long wait_task_inactive(struct task_struct *p, long match_state)
  1039. {
  1040. unsigned long flags;
  1041. int running, queued;
  1042. unsigned long ncsw;
  1043. struct rq *rq;
  1044. for (;;) {
  1045. /*
  1046. * We do the initial early heuristics without holding
  1047. * any task-queue locks at all. We'll only try to get
  1048. * the runqueue lock when things look like they will
  1049. * work out!
  1050. */
  1051. rq = task_rq(p);
  1052. /*
  1053. * If the task is actively running on another CPU
  1054. * still, just relax and busy-wait without holding
  1055. * any locks.
  1056. *
  1057. * NOTE! Since we don't hold any locks, it's not
  1058. * even sure that "rq" stays as the right runqueue!
  1059. * But we don't care, since "task_running()" will
  1060. * return false if the runqueue has changed and p
  1061. * is actually now running somewhere else!
  1062. */
  1063. while (task_running(rq, p)) {
  1064. if (match_state && unlikely(p->state != match_state))
  1065. return 0;
  1066. cpu_relax();
  1067. }
  1068. /*
  1069. * Ok, time to look more closely! We need the rq
  1070. * lock now, to be *sure*. If we're wrong, we'll
  1071. * just go back and repeat.
  1072. */
  1073. rq = task_rq_lock(p, &flags);
  1074. trace_sched_wait_task(p);
  1075. running = task_running(rq, p);
  1076. queued = task_on_rq_queued(p);
  1077. ncsw = 0;
  1078. if (!match_state || p->state == match_state)
  1079. ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
  1080. task_rq_unlock(rq, p, &flags);
  1081. /*
  1082. * If it changed from the expected state, bail out now.
  1083. */
  1084. if (unlikely(!ncsw))
  1085. break;
  1086. /*
  1087. * Was it really running after all now that we
  1088. * checked with the proper locks actually held?
  1089. *
  1090. * Oops. Go back and try again..
  1091. */
  1092. if (unlikely(running)) {
  1093. cpu_relax();
  1094. continue;
  1095. }
  1096. /*
  1097. * It's not enough that it's not actively running,
  1098. * it must be off the runqueue _entirely_, and not
  1099. * preempted!
  1100. *
  1101. * So if it was still runnable (but just not actively
  1102. * running right now), it's preempted, and we should
  1103. * yield - it could be a while.
  1104. */
  1105. if (unlikely(queued)) {
  1106. ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ);
  1107. set_current_state(TASK_UNINTERRUPTIBLE);
  1108. schedule_hrtimeout(&to, HRTIMER_MODE_REL);
  1109. continue;
  1110. }
  1111. /*
  1112. * Ahh, all good. It wasn't running, and it wasn't
  1113. * runnable, which means that it will never become
  1114. * running in the future either. We're all done!
  1115. */
  1116. break;
  1117. }
  1118. return ncsw;
  1119. }
  1120. /***
  1121. * kick_process - kick a running thread to enter/exit the kernel
  1122. * @p: the to-be-kicked thread
  1123. *
  1124. * Cause a process which is running on another CPU to enter
  1125. * kernel-mode, without any delay. (to get signals handled.)
  1126. *
  1127. * NOTE: this function doesn't have to take the runqueue lock,
  1128. * because all it wants to ensure is that the remote task enters
  1129. * the kernel. If the IPI races and the task has been migrated
  1130. * to another CPU then no harm is done and the purpose has been
  1131. * achieved as well.
  1132. */
  1133. void kick_process(struct task_struct *p)
  1134. {
  1135. int cpu;
  1136. preempt_disable();
  1137. cpu = task_cpu(p);
  1138. if ((cpu != smp_processor_id()) && task_curr(p))
  1139. smp_send_reschedule(cpu);
  1140. preempt_enable();
  1141. }
  1142. EXPORT_SYMBOL_GPL(kick_process);
  1143. #endif /* CONFIG_SMP */
  1144. #ifdef CONFIG_SMP
  1145. /*
  1146. * ->cpus_allowed is protected by both rq->lock and p->pi_lock
  1147. */
  1148. static int select_fallback_rq(int cpu, struct task_struct *p)
  1149. {
  1150. int nid = cpu_to_node(cpu);
  1151. const struct cpumask *nodemask = NULL;
  1152. enum { cpuset, possible, fail } state = cpuset;
  1153. int dest_cpu;
  1154. /*
  1155. * If the node that the cpu is on has been offlined, cpu_to_node()
  1156. * will return -1. There is no cpu on the node, and we should
  1157. * select the cpu on the other node.
  1158. */
  1159. if (nid != -1) {
  1160. nodemask = cpumask_of_node(nid);
  1161. /* Look for allowed, online CPU in same node. */
  1162. for_each_cpu(dest_cpu, nodemask) {
  1163. if (!cpu_online(dest_cpu))
  1164. continue;
  1165. if (!cpu_active(dest_cpu))
  1166. continue;
  1167. if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
  1168. return dest_cpu;
  1169. }
  1170. }
  1171. for (;;) {
  1172. /* Any allowed, online CPU? */
  1173. for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) {
  1174. if (!cpu_online(dest_cpu))
  1175. continue;
  1176. if (!cpu_active(dest_cpu))
  1177. continue;
  1178. goto out;
  1179. }
  1180. switch (state) {
  1181. case cpuset:
  1182. /* No more Mr. Nice Guy. */
  1183. cpuset_cpus_allowed_fallback(p);
  1184. state = possible;
  1185. break;
  1186. case possible:
  1187. do_set_cpus_allowed(p, cpu_possible_mask);
  1188. state = fail;
  1189. break;
  1190. case fail:
  1191. BUG();
  1192. break;
  1193. }
  1194. }
  1195. out:
  1196. if (state != cpuset) {
  1197. /*
  1198. * Don't tell them about moving exiting tasks or
  1199. * kernel threads (both mm NULL), since they never
  1200. * leave kernel.
  1201. */
  1202. if (p->mm && printk_ratelimit()) {
  1203. printk_deferred("process %d (%s) no longer affine to cpu%d\n",
  1204. task_pid_nr(p), p->comm, cpu);
  1205. }
  1206. }
  1207. return dest_cpu;
  1208. }
  1209. /*
  1210. * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
  1211. */
  1212. static inline
  1213. int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
  1214. {
  1215. if (p->nr_cpus_allowed > 1)
  1216. cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
  1217. /*
  1218. * In order not to call set_task_cpu() on a blocking task we need
  1219. * to rely on ttwu() to place the task on a valid ->cpus_allowed
  1220. * cpu.
  1221. *
  1222. * Since this is common to all placement strategies, this lives here.
  1223. *
  1224. * [ this allows ->select_task() to simply return task_cpu(p) and
  1225. * not worry about this generic constraint ]
  1226. */
  1227. if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) ||
  1228. !cpu_online(cpu)))
  1229. cpu = select_fallback_rq(task_cpu(p), p);
  1230. return cpu;
  1231. }
  1232. static void update_avg(u64 *avg, u64 sample)
  1233. {
  1234. s64 diff = sample - *avg;
  1235. *avg += diff >> 3;
  1236. }
  1237. #endif
  1238. static void
  1239. ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
  1240. {
  1241. #ifdef CONFIG_SCHEDSTATS
  1242. struct rq *rq = this_rq();
  1243. #ifdef CONFIG_SMP
  1244. int this_cpu = smp_processor_id();
  1245. if (cpu == this_cpu) {
  1246. schedstat_inc(rq, ttwu_local);
  1247. schedstat_inc(p, se.statistics.nr_wakeups_local);
  1248. } else {
  1249. struct sched_domain *sd;
  1250. schedstat_inc(p, se.statistics.nr_wakeups_remote);
  1251. rcu_read_lock();
  1252. for_each_domain(this_cpu, sd) {
  1253. if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  1254. schedstat_inc(sd, ttwu_wake_remote);
  1255. break;
  1256. }
  1257. }
  1258. rcu_read_unlock();
  1259. }
  1260. if (wake_flags & WF_MIGRATED)
  1261. schedstat_inc(p, se.statistics.nr_wakeups_migrate);
  1262. #endif /* CONFIG_SMP */
  1263. schedstat_inc(rq, ttwu_count);
  1264. schedstat_inc(p, se.statistics.nr_wakeups);
  1265. if (wake_flags & WF_SYNC)
  1266. schedstat_inc(p, se.statistics.nr_wakeups_sync);
  1267. #endif /* CONFIG_SCHEDSTATS */
  1268. }
  1269. static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
  1270. {
  1271. activate_task(rq, p, en_flags);
  1272. p->on_rq = TASK_ON_RQ_QUEUED;
  1273. /* if a worker is waking up, notify workqueue */
  1274. if (p->flags & PF_WQ_WORKER)
  1275. wq_worker_waking_up(p, cpu_of(rq));
  1276. }
  1277. /*
  1278. * Mark the task runnable and perform wakeup-preemption.
  1279. */
  1280. static void
  1281. ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags)
  1282. {
  1283. check_preempt_curr(rq, p, wake_flags);
  1284. trace_sched_wakeup(p, true);
  1285. p->state = TASK_RUNNING;
  1286. #ifdef CONFIG_SMP
  1287. if (p->sched_class->task_woken)
  1288. p->sched_class->task_woken(rq, p);
  1289. if (rq->idle_stamp) {
  1290. u64 delta = rq_clock(rq) - rq->idle_stamp;
  1291. u64 max = 2*rq->max_idle_balance_cost;
  1292. update_avg(&rq->avg_idle, delta);
  1293. if (rq->avg_idle > max)
  1294. rq->avg_idle = max;
  1295. rq->idle_stamp = 0;
  1296. }
  1297. #endif
  1298. }
  1299. static void
  1300. ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags)
  1301. {
  1302. #ifdef CONFIG_SMP
  1303. if (p->sched_contributes_to_load)
  1304. rq->nr_uninterruptible--;
  1305. #endif
  1306. ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING);
  1307. ttwu_do_wakeup(rq, p, wake_flags);
  1308. }
  1309. /*
  1310. * Called in case the task @p isn't fully descheduled from its runqueue,
  1311. * in this case we must do a remote wakeup. Its a 'light' wakeup though,
  1312. * since all we need to do is flip p->state to TASK_RUNNING, since
  1313. * the task is still ->on_rq.
  1314. */
  1315. static int ttwu_remote(struct task_struct *p, int wake_flags)
  1316. {
  1317. struct rq *rq;
  1318. int ret = 0;
  1319. rq = __task_rq_lock(p);
  1320. if (task_on_rq_queued(p)) {
  1321. /* check_preempt_curr() may use rq clock */
  1322. update_rq_clock(rq);
  1323. ttwu_do_wakeup(rq, p, wake_flags);
  1324. ret = 1;
  1325. }
  1326. __task_rq_unlock(rq);
  1327. return ret;
  1328. }
  1329. #ifdef CONFIG_SMP
  1330. void sched_ttwu_pending(void)
  1331. {
  1332. struct rq *rq = this_rq();
  1333. struct llist_node *llist = llist_del_all(&rq->wake_list);
  1334. struct task_struct *p;
  1335. unsigned long flags;
  1336. if (!llist)
  1337. return;
  1338. raw_spin_lock_irqsave(&rq->lock, flags);
  1339. while (llist) {
  1340. p = llist_entry(llist, struct task_struct, wake_entry);
  1341. llist = llist_next(llist);
  1342. ttwu_do_activate(rq, p, 0);
  1343. }
  1344. raw_spin_unlock_irqrestore(&rq->lock, flags);
  1345. }
  1346. void scheduler_ipi(void)
  1347. {
  1348. /*
  1349. * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
  1350. * TIF_NEED_RESCHED remotely (for the first time) will also send
  1351. * this IPI.
  1352. */
  1353. preempt_fold_need_resched();
  1354. if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
  1355. return;
  1356. /*
  1357. * Not all reschedule IPI handlers call irq_enter/irq_exit, since
  1358. * traditionally all their work was done from the interrupt return
  1359. * path. Now that we actually do some work, we need to make sure
  1360. * we do call them.
  1361. *
  1362. * Some archs already do call them, luckily irq_enter/exit nest
  1363. * properly.
  1364. *
  1365. * Arguably we should visit all archs and update all handlers,
  1366. * however a fair share of IPIs are still resched only so this would
  1367. * somewhat pessimize the simple resched case.
  1368. */
  1369. irq_enter();
  1370. sched_ttwu_pending();
  1371. /*
  1372. * Check if someone kicked us for doing the nohz idle load balance.
  1373. */
  1374. if (unlikely(got_nohz_idle_kick())) {
  1375. this_rq()->idle_balance = 1;
  1376. raise_softirq_irqoff(SCHED_SOFTIRQ);
  1377. }
  1378. irq_exit();
  1379. }
  1380. static void ttwu_queue_remote(struct task_struct *p, int cpu)
  1381. {
  1382. struct rq *rq = cpu_rq(cpu);
  1383. if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
  1384. if (!set_nr_if_polling(rq->idle))
  1385. smp_send_reschedule(cpu);
  1386. else
  1387. trace_sched_wake_idle_without_ipi(cpu);
  1388. }
  1389. }
  1390. void wake_up_if_idle(int cpu)
  1391. {
  1392. struct rq *rq = cpu_rq(cpu);
  1393. unsigned long flags;
  1394. rcu_read_lock();
  1395. if (!is_idle_task(rcu_dereference(rq->curr)))
  1396. goto out;
  1397. if (set_nr_if_polling(rq->idle)) {
  1398. trace_sched_wake_idle_without_ipi(cpu);
  1399. } else {
  1400. raw_spin_lock_irqsave(&rq->lock, flags);
  1401. if (is_idle_task(rq->curr))
  1402. smp_send_reschedule(cpu);
  1403. /* Else cpu is not in idle, do nothing here */
  1404. raw_spin_unlock_irqrestore(&rq->lock, flags);
  1405. }
  1406. out:
  1407. rcu_read_unlock();
  1408. }
  1409. bool cpus_share_cache(int this_cpu, int that_cpu)
  1410. {
  1411. return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
  1412. }
  1413. #endif /* CONFIG_SMP */
  1414. static void ttwu_queue(struct task_struct *p, int cpu)
  1415. {
  1416. struct rq *rq = cpu_rq(cpu);
  1417. #if defined(CONFIG_SMP)
  1418. if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
  1419. sched_clock_cpu(cpu); /* sync clocks x-cpu */
  1420. ttwu_queue_remote(p, cpu);
  1421. return;
  1422. }
  1423. #endif
  1424. raw_spin_lock(&rq->lock);
  1425. ttwu_do_activate(rq, p, 0);
  1426. raw_spin_unlock(&rq->lock);
  1427. }
  1428. /**
  1429. * try_to_wake_up - wake up a thread
  1430. * @p: the thread to be awakened
  1431. * @state: the mask of task states that can be woken
  1432. * @wake_flags: wake modifier flags (WF_*)
  1433. *
  1434. * Put it on the run-queue if it's not already there. The "current"
  1435. * thread is always on the run-queue (except when the actual
  1436. * re-schedule is in progress), and as such you're allowed to do
  1437. * the simpler "current->state = TASK_RUNNING" to mark yourself
  1438. * runnable without the overhead of this.
  1439. *
  1440. * Return: %true if @p was woken up, %false if it was already running.
  1441. * or @state didn't match @p's state.
  1442. */
  1443. static int
  1444. try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
  1445. {
  1446. unsigned long flags;
  1447. int cpu, success = 0;
  1448. /*
  1449. * If we are going to wake up a thread waiting for CONDITION we
  1450. * need to ensure that CONDITION=1 done by the caller can not be
  1451. * reordered with p->state check below. This pairs with mb() in
  1452. * set_current_state() the waiting thread does.
  1453. */
  1454. smp_mb__before_spinlock();
  1455. raw_spin_lock_irqsave(&p->pi_lock, flags);
  1456. if (!(p->state & state))
  1457. goto out;
  1458. success = 1; /* we're going to change ->state */
  1459. cpu = task_cpu(p);
  1460. if (p->on_rq && ttwu_remote(p, wake_flags))
  1461. goto stat;
  1462. #ifdef CONFIG_SMP
  1463. /*
  1464. * If the owning (remote) cpu is still in the middle of schedule() with
  1465. * this task as prev, wait until its done referencing the task.
  1466. */
  1467. while (p->on_cpu)
  1468. cpu_relax();
  1469. /*
  1470. * Pairs with the smp_wmb() in finish_lock_switch().
  1471. */
  1472. smp_rmb();
  1473. p->sched_contributes_to_load = !!task_contributes_to_load(p);
  1474. p->state = TASK_WAKING;
  1475. if (p->sched_class->task_waking)
  1476. p->sched_class->task_waking(p);
  1477. cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
  1478. if (task_cpu(p) != cpu) {
  1479. wake_flags |= WF_MIGRATED;
  1480. set_task_cpu(p, cpu);
  1481. }
  1482. #endif /* CONFIG_SMP */
  1483. ttwu_queue(p, cpu);
  1484. stat:
  1485. ttwu_stat(p, cpu, wake_flags);
  1486. out:
  1487. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  1488. return success;
  1489. }
  1490. /**
  1491. * try_to_wake_up_local - try to wake up a local task with rq lock held
  1492. * @p: the thread to be awakened
  1493. *
  1494. * Put @p on the run-queue if it's not already there. The caller must
  1495. * ensure that this_rq() is locked, @p is bound to this_rq() and not
  1496. * the current task.
  1497. */
  1498. static void try_to_wake_up_local(struct task_struct *p)
  1499. {
  1500. struct rq *rq = task_rq(p);
  1501. if (WARN_ON_ONCE(rq != this_rq()) ||
  1502. WARN_ON_ONCE(p == current))
  1503. return;
  1504. lockdep_assert_held(&rq->lock);
  1505. if (!raw_spin_trylock(&p->pi_lock)) {
  1506. raw_spin_unlock(&rq->lock);
  1507. raw_spin_lock(&p->pi_lock);
  1508. raw_spin_lock(&rq->lock);
  1509. }
  1510. if (!(p->state & TASK_NORMAL))
  1511. goto out;
  1512. if (!task_on_rq_queued(p))
  1513. ttwu_activate(rq, p, ENQUEUE_WAKEUP);
  1514. ttwu_do_wakeup(rq, p, 0);
  1515. ttwu_stat(p, smp_processor_id(), 0);
  1516. out:
  1517. raw_spin_unlock(&p->pi_lock);
  1518. }
  1519. /**
  1520. * wake_up_process - Wake up a specific process
  1521. * @p: The process to be woken up.
  1522. *
  1523. * Attempt to wake up the nominated process and move it to the set of runnable
  1524. * processes.
  1525. *
  1526. * Return: 1 if the process was woken up, 0 if it was already running.
  1527. *
  1528. * It may be assumed that this function implies a write memory barrier before
  1529. * changing the task state if and only if any tasks are woken up.
  1530. */
  1531. int wake_up_process(struct task_struct *p)
  1532. {
  1533. WARN_ON(task_is_stopped_or_traced(p));
  1534. return try_to_wake_up(p, TASK_NORMAL, 0);
  1535. }
  1536. EXPORT_SYMBOL(wake_up_process);
  1537. int wake_up_state(struct task_struct *p, unsigned int state)
  1538. {
  1539. return try_to_wake_up(p, state, 0);
  1540. }
  1541. /*
  1542. * This function clears the sched_dl_entity static params.
  1543. */
  1544. void __dl_clear_params(struct task_struct *p)
  1545. {
  1546. struct sched_dl_entity *dl_se = &p->dl;
  1547. dl_se->dl_runtime = 0;
  1548. dl_se->dl_deadline = 0;
  1549. dl_se->dl_period = 0;
  1550. dl_se->flags = 0;
  1551. dl_se->dl_bw = 0;
  1552. dl_se->dl_throttled = 0;
  1553. dl_se->dl_new = 1;
  1554. dl_se->dl_yielded = 0;
  1555. }
  1556. /*
  1557. * Perform scheduler related setup for a newly forked process p.
  1558. * p is forked by current.
  1559. *
  1560. * __sched_fork() is basic setup used by init_idle() too:
  1561. */
  1562. static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
  1563. {
  1564. p->on_rq = 0;
  1565. p->se.on_rq = 0;
  1566. p->se.exec_start = 0;
  1567. p->se.sum_exec_runtime = 0;
  1568. p->se.prev_sum_exec_runtime = 0;
  1569. p->se.nr_migrations = 0;
  1570. p->se.vruntime = 0;
  1571. #ifdef CONFIG_SMP
  1572. p->se.avg.decay_count = 0;
  1573. #endif
  1574. INIT_LIST_HEAD(&p->se.group_node);
  1575. #ifdef CONFIG_SCHEDSTATS
  1576. memset(&p->se.statistics, 0, sizeof(p->se.statistics));
  1577. #endif
  1578. RB_CLEAR_NODE(&p->dl.rb_node);
  1579. init_dl_task_timer(&p->dl);
  1580. __dl_clear_params(p);
  1581. INIT_LIST_HEAD(&p->rt.run_list);
  1582. #ifdef CONFIG_PREEMPT_NOTIFIERS
  1583. INIT_HLIST_HEAD(&p->preempt_notifiers);
  1584. #endif
  1585. #ifdef CONFIG_NUMA_BALANCING
  1586. if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
  1587. p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  1588. p->mm->numa_scan_seq = 0;
  1589. }
  1590. if (clone_flags & CLONE_VM)
  1591. p->numa_preferred_nid = current->numa_preferred_nid;
  1592. else
  1593. p->numa_preferred_nid = -1;
  1594. p->node_stamp = 0ULL;
  1595. p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
  1596. p->numa_scan_period = sysctl_numa_balancing_scan_delay;
  1597. p->numa_work.next = &p->numa_work;
  1598. p->numa_faults = NULL;
  1599. p->last_task_numa_placement = 0;
  1600. p->last_sum_exec_runtime = 0;
  1601. p->numa_group = NULL;
  1602. #endif /* CONFIG_NUMA_BALANCING */
  1603. }
  1604. #ifdef CONFIG_NUMA_BALANCING
  1605. #ifdef CONFIG_SCHED_DEBUG
  1606. void set_numabalancing_state(bool enabled)
  1607. {
  1608. if (enabled)
  1609. sched_feat_set("NUMA");
  1610. else
  1611. sched_feat_set("NO_NUMA");
  1612. }
  1613. #else
  1614. __read_mostly bool numabalancing_enabled;
  1615. void set_numabalancing_state(bool enabled)
  1616. {
  1617. numabalancing_enabled = enabled;
  1618. }
  1619. #endif /* CONFIG_SCHED_DEBUG */
  1620. #ifdef CONFIG_PROC_SYSCTL
  1621. int sysctl_numa_balancing(struct ctl_table *table, int write,
  1622. void __user *buffer, size_t *lenp, loff_t *ppos)
  1623. {
  1624. struct ctl_table t;
  1625. int err;
  1626. int state = numabalancing_enabled;
  1627. if (write && !capable(CAP_SYS_ADMIN))
  1628. return -EPERM;
  1629. t = *table;
  1630. t.data = &state;
  1631. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  1632. if (err < 0)
  1633. return err;
  1634. if (write)
  1635. set_numabalancing_state(state);
  1636. return err;
  1637. }
  1638. #endif
  1639. #endif
  1640. /*
  1641. * fork()/clone()-time setup:
  1642. */
  1643. int sched_fork(unsigned long clone_flags, struct task_struct *p)
  1644. {
  1645. unsigned long flags;
  1646. int cpu = get_cpu();
  1647. __sched_fork(clone_flags, p);
  1648. /*
  1649. * We mark the process as running here. This guarantees that
  1650. * nobody will actually run it, and a signal or other external
  1651. * event cannot wake it up and insert it on the runqueue either.
  1652. */
  1653. p->state = TASK_RUNNING;
  1654. /*
  1655. * Make sure we do not leak PI boosting priority to the child.
  1656. */
  1657. p->prio = current->normal_prio;
  1658. /*
  1659. * Revert to default priority/policy on fork if requested.
  1660. */
  1661. if (unlikely(p->sched_reset_on_fork)) {
  1662. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  1663. p->policy = SCHED_NORMAL;
  1664. p->static_prio = NICE_TO_PRIO(0);
  1665. p->rt_priority = 0;
  1666. } else if (PRIO_TO_NICE(p->static_prio) < 0)
  1667. p->static_prio = NICE_TO_PRIO(0);
  1668. p->prio = p->normal_prio = __normal_prio(p);
  1669. set_load_weight(p);
  1670. /*
  1671. * We don't need the reset flag anymore after the fork. It has
  1672. * fulfilled its duty:
  1673. */
  1674. p->sched_reset_on_fork = 0;
  1675. }
  1676. if (dl_prio(p->prio)) {
  1677. put_cpu();
  1678. return -EAGAIN;
  1679. } else if (rt_prio(p->prio)) {
  1680. p->sched_class = &rt_sched_class;
  1681. } else {
  1682. p->sched_class = &fair_sched_class;
  1683. }
  1684. if (p->sched_class->task_fork)
  1685. p->sched_class->task_fork(p);
  1686. /*
  1687. * The child is not yet in the pid-hash so no cgroup attach races,
  1688. * and the cgroup is pinned to this child due to cgroup_fork()
  1689. * is ran before sched_fork().
  1690. *
  1691. * Silence PROVE_RCU.
  1692. */
  1693. raw_spin_lock_irqsave(&p->pi_lock, flags);
  1694. set_task_cpu(p, cpu);
  1695. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  1696. #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
  1697. if (likely(sched_info_on()))
  1698. memset(&p->sched_info, 0, sizeof(p->sched_info));
  1699. #endif
  1700. #if defined(CONFIG_SMP)
  1701. p->on_cpu = 0;
  1702. #endif
  1703. init_task_preempt_count(p);
  1704. #ifdef CONFIG_SMP
  1705. plist_node_init(&p->pushable_tasks, MAX_PRIO);
  1706. RB_CLEAR_NODE(&p->pushable_dl_tasks);
  1707. #endif
  1708. put_cpu();
  1709. return 0;
  1710. }
  1711. unsigned long to_ratio(u64 period, u64 runtime)
  1712. {
  1713. if (runtime == RUNTIME_INF)
  1714. return 1ULL << 20;
  1715. /*
  1716. * Doing this here saves a lot of checks in all
  1717. * the calling paths, and returning zero seems
  1718. * safe for them anyway.
  1719. */
  1720. if (period == 0)
  1721. return 0;
  1722. return div64_u64(runtime << 20, period);
  1723. }
  1724. #ifdef CONFIG_SMP
  1725. inline struct dl_bw *dl_bw_of(int i)
  1726. {
  1727. rcu_lockdep_assert(rcu_read_lock_sched_held(),
  1728. "sched RCU must be held");
  1729. return &cpu_rq(i)->rd->dl_bw;
  1730. }
  1731. static inline int dl_bw_cpus(int i)
  1732. {
  1733. struct root_domain *rd = cpu_rq(i)->rd;
  1734. int cpus = 0;
  1735. rcu_lockdep_assert(rcu_read_lock_sched_held(),
  1736. "sched RCU must be held");
  1737. for_each_cpu_and(i, rd->span, cpu_active_mask)
  1738. cpus++;
  1739. return cpus;
  1740. }
  1741. #else
  1742. inline struct dl_bw *dl_bw_of(int i)
  1743. {
  1744. return &cpu_rq(i)->dl.dl_bw;
  1745. }
  1746. static inline int dl_bw_cpus(int i)
  1747. {
  1748. return 1;
  1749. }
  1750. #endif
  1751. /*
  1752. * We must be sure that accepting a new task (or allowing changing the
  1753. * parameters of an existing one) is consistent with the bandwidth
  1754. * constraints. If yes, this function also accordingly updates the currently
  1755. * allocated bandwidth to reflect the new situation.
  1756. *
  1757. * This function is called while holding p's rq->lock.
  1758. *
  1759. * XXX we should delay bw change until the task's 0-lag point, see
  1760. * __setparam_dl().
  1761. */
  1762. static int dl_overflow(struct task_struct *p, int policy,
  1763. const struct sched_attr *attr)
  1764. {
  1765. struct dl_bw *dl_b = dl_bw_of(task_cpu(p));
  1766. u64 period = attr->sched_period ?: attr->sched_deadline;
  1767. u64 runtime = attr->sched_runtime;
  1768. u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0;
  1769. int cpus, err = -1;
  1770. if (new_bw == p->dl.dl_bw)
  1771. return 0;
  1772. /*
  1773. * Either if a task, enters, leave, or stays -deadline but changes
  1774. * its parameters, we may need to update accordingly the total
  1775. * allocated bandwidth of the container.
  1776. */
  1777. raw_spin_lock(&dl_b->lock);
  1778. cpus = dl_bw_cpus(task_cpu(p));
  1779. if (dl_policy(policy) && !task_has_dl_policy(p) &&
  1780. !__dl_overflow(dl_b, cpus, 0, new_bw)) {
  1781. __dl_add(dl_b, new_bw);
  1782. err = 0;
  1783. } else if (dl_policy(policy) && task_has_dl_policy(p) &&
  1784. !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) {
  1785. __dl_clear(dl_b, p->dl.dl_bw);
  1786. __dl_add(dl_b, new_bw);
  1787. err = 0;
  1788. } else if (!dl_policy(policy) && task_has_dl_policy(p)) {
  1789. __dl_clear(dl_b, p->dl.dl_bw);
  1790. err = 0;
  1791. }
  1792. raw_spin_unlock(&dl_b->lock);
  1793. return err;
  1794. }
  1795. extern void init_dl_bw(struct dl_bw *dl_b);
  1796. /*
  1797. * wake_up_new_task - wake up a newly created task for the first time.
  1798. *
  1799. * This function will do some initial scheduler statistics housekeeping
  1800. * that must be done for every newly created context, then puts the task
  1801. * on the runqueue and wakes it.
  1802. */
  1803. void wake_up_new_task(struct task_struct *p)
  1804. {
  1805. unsigned long flags;
  1806. struct rq *rq;
  1807. raw_spin_lock_irqsave(&p->pi_lock, flags);
  1808. #ifdef CONFIG_SMP
  1809. /*
  1810. * Fork balancing, do it here and not earlier because:
  1811. * - cpus_allowed can change in the fork path
  1812. * - any previously selected cpu might disappear through hotplug
  1813. */
  1814. set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
  1815. #endif
  1816. /* Initialize new task's runnable average */
  1817. init_task_runnable_average(p);
  1818. rq = __task_rq_lock(p);
  1819. activate_task(rq, p, 0);
  1820. p->on_rq = TASK_ON_RQ_QUEUED;
  1821. trace_sched_wakeup_new(p, true);
  1822. check_preempt_curr(rq, p, WF_FORK);
  1823. #ifdef CONFIG_SMP
  1824. if (p->sched_class->task_woken)
  1825. p->sched_class->task_woken(rq, p);
  1826. #endif
  1827. task_rq_unlock(rq, p, &flags);
  1828. }
  1829. #ifdef CONFIG_PREEMPT_NOTIFIERS
  1830. /**
  1831. * preempt_notifier_register - tell me when current is being preempted & rescheduled
  1832. * @notifier: notifier struct to register
  1833. */
  1834. void preempt_notifier_register(struct preempt_notifier *notifier)
  1835. {
  1836. hlist_add_head(&notifier->link, &current->preempt_notifiers);
  1837. }
  1838. EXPORT_SYMBOL_GPL(preempt_notifier_register);
  1839. /**
  1840. * preempt_notifier_unregister - no longer interested in preemption notifications
  1841. * @notifier: notifier struct to unregister
  1842. *
  1843. * This is safe to call from within a preemption notifier.
  1844. */
  1845. void preempt_notifier_unregister(struct preempt_notifier *notifier)
  1846. {
  1847. hlist_del(&notifier->link);
  1848. }
  1849. EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
  1850. static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  1851. {
  1852. struct preempt_notifier *notifier;
  1853. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  1854. notifier->ops->sched_in(notifier, raw_smp_processor_id());
  1855. }
  1856. static void
  1857. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  1858. struct task_struct *next)
  1859. {
  1860. struct preempt_notifier *notifier;
  1861. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  1862. notifier->ops->sched_out(notifier, next);
  1863. }
  1864. #else /* !CONFIG_PREEMPT_NOTIFIERS */
  1865. static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  1866. {
  1867. }
  1868. static void
  1869. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  1870. struct task_struct *next)
  1871. {
  1872. }
  1873. #endif /* CONFIG_PREEMPT_NOTIFIERS */
  1874. /**
  1875. * prepare_task_switch - prepare to switch tasks
  1876. * @rq: the runqueue preparing to switch
  1877. * @prev: the current task that is being switched out
  1878. * @next: the task we are going to switch to.
  1879. *
  1880. * This is called with the rq lock held and interrupts off. It must
  1881. * be paired with a subsequent finish_task_switch after the context
  1882. * switch.
  1883. *
  1884. * prepare_task_switch sets up locking and calls architecture specific
  1885. * hooks.
  1886. */
  1887. static inline void
  1888. prepare_task_switch(struct rq *rq, struct task_struct *prev,
  1889. struct task_struct *next)
  1890. {
  1891. trace_sched_switch(prev, next);
  1892. sched_info_switch(rq, prev, next);
  1893. perf_event_task_sched_out(prev, next);
  1894. fire_sched_out_preempt_notifiers(prev, next);
  1895. prepare_lock_switch(rq, next);
  1896. prepare_arch_switch(next);
  1897. }
  1898. /**
  1899. * finish_task_switch - clean up after a task-switch
  1900. * @prev: the thread we just switched away from.
  1901. *
  1902. * finish_task_switch must be called after the context switch, paired
  1903. * with a prepare_task_switch call before the context switch.
  1904. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  1905. * and do any other architecture-specific cleanup actions.
  1906. *
  1907. * Note that we may have delayed dropping an mm in context_switch(). If
  1908. * so, we finish that here outside of the runqueue lock. (Doing it
  1909. * with the lock held can cause deadlocks; see schedule() for
  1910. * details.)
  1911. *
  1912. * The context switch have flipped the stack from under us and restored the
  1913. * local variables which were saved when this task called schedule() in the
  1914. * past. prev == current is still correct but we need to recalculate this_rq
  1915. * because prev may have moved to another CPU.
  1916. */
  1917. static struct rq *finish_task_switch(struct task_struct *prev)
  1918. __releases(rq->lock)
  1919. {
  1920. struct rq *rq = this_rq();
  1921. struct mm_struct *mm = rq->prev_mm;
  1922. long prev_state;
  1923. rq->prev_mm = NULL;
  1924. /*
  1925. * A task struct has one reference for the use as "current".
  1926. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  1927. * schedule one last time. The schedule call will never return, and
  1928. * the scheduled task must drop that reference.
  1929. * The test for TASK_DEAD must occur while the runqueue locks are
  1930. * still held, otherwise prev could be scheduled on another cpu, die
  1931. * there before we look at prev->state, and then the reference would
  1932. * be dropped twice.
  1933. * Manfred Spraul <manfred@colorfullife.com>
  1934. */
  1935. prev_state = prev->state;
  1936. vtime_task_switch(prev);
  1937. finish_arch_switch(prev);
  1938. perf_event_task_sched_in(prev, current);
  1939. finish_lock_switch(rq, prev);
  1940. finish_arch_post_lock_switch();
  1941. fire_sched_in_preempt_notifiers(current);
  1942. if (mm)
  1943. mmdrop(mm);
  1944. if (unlikely(prev_state == TASK_DEAD)) {
  1945. if (prev->sched_class->task_dead)
  1946. prev->sched_class->task_dead(prev);
  1947. /*
  1948. * Remove function-return probe instances associated with this
  1949. * task and put them back on the free list.
  1950. */
  1951. kprobe_flush_task(prev);
  1952. put_task_struct(prev);
  1953. }
  1954. tick_nohz_task_switch(current);
  1955. return rq;
  1956. }
  1957. #ifdef CONFIG_SMP
  1958. /* rq->lock is NOT held, but preemption is disabled */
  1959. static inline void post_schedule(struct rq *rq)
  1960. {
  1961. if (rq->post_schedule) {
  1962. unsigned long flags;
  1963. raw_spin_lock_irqsave(&rq->lock, flags);
  1964. if (rq->curr->sched_class->post_schedule)
  1965. rq->curr->sched_class->post_schedule(rq);
  1966. raw_spin_unlock_irqrestore(&rq->lock, flags);
  1967. rq->post_schedule = 0;
  1968. }
  1969. }
  1970. #else
  1971. static inline void post_schedule(struct rq *rq)
  1972. {
  1973. }
  1974. #endif
  1975. /**
  1976. * schedule_tail - first thing a freshly forked thread must call.
  1977. * @prev: the thread we just switched away from.
  1978. */
  1979. asmlinkage __visible void schedule_tail(struct task_struct *prev)
  1980. __releases(rq->lock)
  1981. {
  1982. struct rq *rq;
  1983. /* finish_task_switch() drops rq->lock and enables preemtion */
  1984. preempt_disable();
  1985. rq = finish_task_switch(prev);
  1986. post_schedule(rq);
  1987. preempt_enable();
  1988. if (current->set_child_tid)
  1989. put_user(task_pid_vnr(current), current->set_child_tid);
  1990. }
  1991. /*
  1992. * context_switch - switch to the new MM and the new thread's register state.
  1993. */
  1994. static inline struct rq *
  1995. context_switch(struct rq *rq, struct task_struct *prev,
  1996. struct task_struct *next)
  1997. {
  1998. struct mm_struct *mm, *oldmm;
  1999. prepare_task_switch(rq, prev, next);
  2000. mm = next->mm;
  2001. oldmm = prev->active_mm;
  2002. /*
  2003. * For paravirt, this is coupled with an exit in switch_to to
  2004. * combine the page table reload and the switch backend into
  2005. * one hypercall.
  2006. */
  2007. arch_start_context_switch(prev);
  2008. if (!mm) {
  2009. next->active_mm = oldmm;
  2010. atomic_inc(&oldmm->mm_count);
  2011. enter_lazy_tlb(oldmm, next);
  2012. } else
  2013. switch_mm(oldmm, mm, next);
  2014. if (!prev->mm) {
  2015. prev->active_mm = NULL;
  2016. rq->prev_mm = oldmm;
  2017. }
  2018. /*
  2019. * Since the runqueue lock will be released by the next
  2020. * task (which is an invalid locking op but in the case
  2021. * of the scheduler it's an obvious special-case), so we
  2022. * do an early lockdep release here:
  2023. */
  2024. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  2025. context_tracking_task_switch(prev, next);
  2026. /* Here we just switch the register state and the stack. */
  2027. switch_to(prev, next, prev);
  2028. barrier();
  2029. return finish_task_switch(prev);
  2030. }
  2031. /*
  2032. * nr_running and nr_context_switches:
  2033. *
  2034. * externally visible scheduler statistics: current number of runnable
  2035. * threads, total number of context switches performed since bootup.
  2036. */
  2037. unsigned long nr_running(void)
  2038. {
  2039. unsigned long i, sum = 0;
  2040. for_each_online_cpu(i)
  2041. sum += cpu_rq(i)->nr_running;
  2042. return sum;
  2043. }
  2044. /*
  2045. * Check if only the current task is running on the cpu.
  2046. */
  2047. bool single_task_running(void)
  2048. {
  2049. if (cpu_rq(smp_processor_id())->nr_running == 1)
  2050. return true;
  2051. else
  2052. return false;
  2053. }
  2054. EXPORT_SYMBOL(single_task_running);
  2055. unsigned long long nr_context_switches(void)
  2056. {
  2057. int i;
  2058. unsigned long long sum = 0;
  2059. for_each_possible_cpu(i)
  2060. sum += cpu_rq(i)->nr_switches;
  2061. return sum;
  2062. }
  2063. unsigned long nr_iowait(void)
  2064. {
  2065. unsigned long i, sum = 0;
  2066. for_each_possible_cpu(i)
  2067. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  2068. return sum;
  2069. }
  2070. unsigned long nr_iowait_cpu(int cpu)
  2071. {
  2072. struct rq *this = cpu_rq(cpu);
  2073. return atomic_read(&this->nr_iowait);
  2074. }
  2075. void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
  2076. {
  2077. struct rq *rq = this_rq();
  2078. *nr_waiters = atomic_read(&rq->nr_iowait);
  2079. *load = rq->load.weight;
  2080. }
  2081. #ifdef CONFIG_SMP
  2082. /*
  2083. * sched_exec - execve() is a valuable balancing opportunity, because at
  2084. * this point the task has the smallest effective memory and cache footprint.
  2085. */
  2086. void sched_exec(void)
  2087. {
  2088. struct task_struct *p = current;
  2089. unsigned long flags;
  2090. int dest_cpu;
  2091. raw_spin_lock_irqsave(&p->pi_lock, flags);
  2092. dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
  2093. if (dest_cpu == smp_processor_id())
  2094. goto unlock;
  2095. if (likely(cpu_active(dest_cpu))) {
  2096. struct migration_arg arg = { p, dest_cpu };
  2097. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2098. stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
  2099. return;
  2100. }
  2101. unlock:
  2102. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2103. }
  2104. #endif
  2105. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2106. DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
  2107. EXPORT_PER_CPU_SYMBOL(kstat);
  2108. EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
  2109. /*
  2110. * Return accounted runtime for the task.
  2111. * In case the task is currently running, return the runtime plus current's
  2112. * pending runtime that have not been accounted yet.
  2113. */
  2114. unsigned long long task_sched_runtime(struct task_struct *p)
  2115. {
  2116. unsigned long flags;
  2117. struct rq *rq;
  2118. u64 ns;
  2119. #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
  2120. /*
  2121. * 64-bit doesn't need locks to atomically read a 64bit value.
  2122. * So we have a optimization chance when the task's delta_exec is 0.
  2123. * Reading ->on_cpu is racy, but this is ok.
  2124. *
  2125. * If we race with it leaving cpu, we'll take a lock. So we're correct.
  2126. * If we race with it entering cpu, unaccounted time is 0. This is
  2127. * indistinguishable from the read occurring a few cycles earlier.
  2128. * If we see ->on_cpu without ->on_rq, the task is leaving, and has
  2129. * been accounted, so we're correct here as well.
  2130. */
  2131. if (!p->on_cpu || !task_on_rq_queued(p))
  2132. return p->se.sum_exec_runtime;
  2133. #endif
  2134. rq = task_rq_lock(p, &flags);
  2135. /*
  2136. * Must be ->curr _and_ ->on_rq. If dequeued, we would
  2137. * project cycles that may never be accounted to this
  2138. * thread, breaking clock_gettime().
  2139. */
  2140. if (task_current(rq, p) && task_on_rq_queued(p)) {
  2141. update_rq_clock(rq);
  2142. p->sched_class->update_curr(rq);
  2143. }
  2144. ns = p->se.sum_exec_runtime;
  2145. task_rq_unlock(rq, p, &flags);
  2146. return ns;
  2147. }
  2148. /*
  2149. * This function gets called by the timer code, with HZ frequency.
  2150. * We call it with interrupts disabled.
  2151. */
  2152. void scheduler_tick(void)
  2153. {
  2154. int cpu = smp_processor_id();
  2155. struct rq *rq = cpu_rq(cpu);
  2156. struct task_struct *curr = rq->curr;
  2157. sched_clock_tick();
  2158. raw_spin_lock(&rq->lock);
  2159. update_rq_clock(rq);
  2160. curr->sched_class->task_tick(rq, curr, 0);
  2161. update_cpu_load_active(rq);
  2162. calc_global_load_tick(rq);
  2163. raw_spin_unlock(&rq->lock);
  2164. perf_event_task_tick();
  2165. #ifdef CONFIG_SMP
  2166. rq->idle_balance = idle_cpu(cpu);
  2167. trigger_load_balance(rq);
  2168. #endif
  2169. rq_last_tick_reset(rq);
  2170. }
  2171. #ifdef CONFIG_NO_HZ_FULL
  2172. /**
  2173. * scheduler_tick_max_deferment
  2174. *
  2175. * Keep at least one tick per second when a single
  2176. * active task is running because the scheduler doesn't
  2177. * yet completely support full dynticks environment.
  2178. *
  2179. * This makes sure that uptime, CFS vruntime, load
  2180. * balancing, etc... continue to move forward, even
  2181. * with a very low granularity.
  2182. *
  2183. * Return: Maximum deferment in nanoseconds.
  2184. */
  2185. u64 scheduler_tick_max_deferment(void)
  2186. {
  2187. struct rq *rq = this_rq();
  2188. unsigned long next, now = READ_ONCE(jiffies);
  2189. next = rq->last_sched_tick + HZ;
  2190. if (time_before_eq(next, now))
  2191. return 0;
  2192. return jiffies_to_nsecs(next - now);
  2193. }
  2194. #endif
  2195. notrace unsigned long get_parent_ip(unsigned long addr)
  2196. {
  2197. if (in_lock_functions(addr)) {
  2198. addr = CALLER_ADDR2;
  2199. if (in_lock_functions(addr))
  2200. addr = CALLER_ADDR3;
  2201. }
  2202. return addr;
  2203. }
  2204. #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
  2205. defined(CONFIG_PREEMPT_TRACER))
  2206. void preempt_count_add(int val)
  2207. {
  2208. #ifdef CONFIG_DEBUG_PREEMPT
  2209. /*
  2210. * Underflow?
  2211. */
  2212. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  2213. return;
  2214. #endif
  2215. __preempt_count_add(val);
  2216. #ifdef CONFIG_DEBUG_PREEMPT
  2217. /*
  2218. * Spinlock count overflowing soon?
  2219. */
  2220. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  2221. PREEMPT_MASK - 10);
  2222. #endif
  2223. if (preempt_count() == val) {
  2224. unsigned long ip = get_parent_ip(CALLER_ADDR1);
  2225. #ifdef CONFIG_DEBUG_PREEMPT
  2226. current->preempt_disable_ip = ip;
  2227. #endif
  2228. trace_preempt_off(CALLER_ADDR0, ip);
  2229. }
  2230. }
  2231. EXPORT_SYMBOL(preempt_count_add);
  2232. NOKPROBE_SYMBOL(preempt_count_add);
  2233. void preempt_count_sub(int val)
  2234. {
  2235. #ifdef CONFIG_DEBUG_PREEMPT
  2236. /*
  2237. * Underflow?
  2238. */
  2239. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  2240. return;
  2241. /*
  2242. * Is the spinlock portion underflowing?
  2243. */
  2244. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  2245. !(preempt_count() & PREEMPT_MASK)))
  2246. return;
  2247. #endif
  2248. if (preempt_count() == val)
  2249. trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
  2250. __preempt_count_sub(val);
  2251. }
  2252. EXPORT_SYMBOL(preempt_count_sub);
  2253. NOKPROBE_SYMBOL(preempt_count_sub);
  2254. #endif
  2255. /*
  2256. * Print scheduling while atomic bug:
  2257. */
  2258. static noinline void __schedule_bug(struct task_struct *prev)
  2259. {
  2260. if (oops_in_progress)
  2261. return;
  2262. printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
  2263. prev->comm, prev->pid, preempt_count());
  2264. debug_show_held_locks(prev);
  2265. print_modules();
  2266. if (irqs_disabled())
  2267. print_irqtrace_events(prev);
  2268. #ifdef CONFIG_DEBUG_PREEMPT
  2269. if (in_atomic_preempt_off()) {
  2270. pr_err("Preemption disabled at:");
  2271. print_ip_sym(current->preempt_disable_ip);
  2272. pr_cont("\n");
  2273. }
  2274. #endif
  2275. dump_stack();
  2276. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  2277. }
  2278. /*
  2279. * Various schedule()-time debugging checks and statistics:
  2280. */
  2281. static inline void schedule_debug(struct task_struct *prev)
  2282. {
  2283. #ifdef CONFIG_SCHED_STACK_END_CHECK
  2284. BUG_ON(unlikely(task_stack_end_corrupted(prev)));
  2285. #endif
  2286. /*
  2287. * Test if we are atomic. Since do_exit() needs to call into
  2288. * schedule() atomically, we ignore that path. Otherwise whine
  2289. * if we are scheduling when we should not.
  2290. */
  2291. if (unlikely(in_atomic_preempt_off() && prev->state != TASK_DEAD))
  2292. __schedule_bug(prev);
  2293. rcu_sleep_check();
  2294. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2295. schedstat_inc(this_rq(), sched_count);
  2296. }
  2297. /*
  2298. * Pick up the highest-prio task:
  2299. */
  2300. static inline struct task_struct *
  2301. pick_next_task(struct rq *rq, struct task_struct *prev)
  2302. {
  2303. const struct sched_class *class = &fair_sched_class;
  2304. struct task_struct *p;
  2305. /*
  2306. * Optimization: we know that if all tasks are in
  2307. * the fair class we can call that function directly:
  2308. */
  2309. if (likely(prev->sched_class == class &&
  2310. rq->nr_running == rq->cfs.h_nr_running)) {
  2311. p = fair_sched_class.pick_next_task(rq, prev);
  2312. if (unlikely(p == RETRY_TASK))
  2313. goto again;
  2314. /* assumes fair_sched_class->next == idle_sched_class */
  2315. if (unlikely(!p))
  2316. p = idle_sched_class.pick_next_task(rq, prev);
  2317. return p;
  2318. }
  2319. again:
  2320. for_each_class(class) {
  2321. p = class->pick_next_task(rq, prev);
  2322. if (p) {
  2323. if (unlikely(p == RETRY_TASK))
  2324. goto again;
  2325. return p;
  2326. }
  2327. }
  2328. BUG(); /* the idle class will always have a runnable task */
  2329. }
  2330. /*
  2331. * __schedule() is the main scheduler function.
  2332. *
  2333. * The main means of driving the scheduler and thus entering this function are:
  2334. *
  2335. * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
  2336. *
  2337. * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
  2338. * paths. For example, see arch/x86/entry_64.S.
  2339. *
  2340. * To drive preemption between tasks, the scheduler sets the flag in timer
  2341. * interrupt handler scheduler_tick().
  2342. *
  2343. * 3. Wakeups don't really cause entry into schedule(). They add a
  2344. * task to the run-queue and that's it.
  2345. *
  2346. * Now, if the new task added to the run-queue preempts the current
  2347. * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
  2348. * called on the nearest possible occasion:
  2349. *
  2350. * - If the kernel is preemptible (CONFIG_PREEMPT=y):
  2351. *
  2352. * - in syscall or exception context, at the next outmost
  2353. * preempt_enable(). (this might be as soon as the wake_up()'s
  2354. * spin_unlock()!)
  2355. *
  2356. * - in IRQ context, return from interrupt-handler to
  2357. * preemptible context
  2358. *
  2359. * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
  2360. * then at the next:
  2361. *
  2362. * - cond_resched() call
  2363. * - explicit schedule() call
  2364. * - return from syscall or exception to user-space
  2365. * - return from interrupt-handler to user-space
  2366. *
  2367. * WARNING: must be called with preemption disabled!
  2368. */
  2369. static void __sched __schedule(void)
  2370. {
  2371. struct task_struct *prev, *next;
  2372. unsigned long *switch_count;
  2373. struct rq *rq;
  2374. int cpu;
  2375. cpu = smp_processor_id();
  2376. rq = cpu_rq(cpu);
  2377. rcu_note_context_switch();
  2378. prev = rq->curr;
  2379. schedule_debug(prev);
  2380. if (sched_feat(HRTICK))
  2381. hrtick_clear(rq);
  2382. /*
  2383. * Make sure that signal_pending_state()->signal_pending() below
  2384. * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
  2385. * done by the caller to avoid the race with signal_wake_up().
  2386. */
  2387. smp_mb__before_spinlock();
  2388. raw_spin_lock_irq(&rq->lock);
  2389. rq->clock_skip_update <<= 1; /* promote REQ to ACT */
  2390. switch_count = &prev->nivcsw;
  2391. if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
  2392. if (unlikely(signal_pending_state(prev->state, prev))) {
  2393. prev->state = TASK_RUNNING;
  2394. } else {
  2395. deactivate_task(rq, prev, DEQUEUE_SLEEP);
  2396. prev->on_rq = 0;
  2397. /*
  2398. * If a worker went to sleep, notify and ask workqueue
  2399. * whether it wants to wake up a task to maintain
  2400. * concurrency.
  2401. */
  2402. if (prev->flags & PF_WQ_WORKER) {
  2403. struct task_struct *to_wakeup;
  2404. to_wakeup = wq_worker_sleeping(prev, cpu);
  2405. if (to_wakeup)
  2406. try_to_wake_up_local(to_wakeup);
  2407. }
  2408. }
  2409. switch_count = &prev->nvcsw;
  2410. }
  2411. if (task_on_rq_queued(prev))
  2412. update_rq_clock(rq);
  2413. next = pick_next_task(rq, prev);
  2414. clear_tsk_need_resched(prev);
  2415. clear_preempt_need_resched();
  2416. rq->clock_skip_update = 0;
  2417. if (likely(prev != next)) {
  2418. rq->nr_switches++;
  2419. rq->curr = next;
  2420. ++*switch_count;
  2421. rq = context_switch(rq, prev, next); /* unlocks the rq */
  2422. cpu = cpu_of(rq);
  2423. } else
  2424. raw_spin_unlock_irq(&rq->lock);
  2425. post_schedule(rq);
  2426. }
  2427. static inline void sched_submit_work(struct task_struct *tsk)
  2428. {
  2429. if (!tsk->state || tsk_is_pi_blocked(tsk))
  2430. return;
  2431. /*
  2432. * If we are going to sleep and we have plugged IO queued,
  2433. * make sure to submit it to avoid deadlocks.
  2434. */
  2435. if (blk_needs_flush_plug(tsk))
  2436. blk_schedule_flush_plug(tsk);
  2437. }
  2438. asmlinkage __visible void __sched schedule(void)
  2439. {
  2440. struct task_struct *tsk = current;
  2441. sched_submit_work(tsk);
  2442. do {
  2443. preempt_disable();
  2444. __schedule();
  2445. sched_preempt_enable_no_resched();
  2446. } while (need_resched());
  2447. }
  2448. EXPORT_SYMBOL(schedule);
  2449. #ifdef CONFIG_CONTEXT_TRACKING
  2450. asmlinkage __visible void __sched schedule_user(void)
  2451. {
  2452. /*
  2453. * If we come here after a random call to set_need_resched(),
  2454. * or we have been woken up remotely but the IPI has not yet arrived,
  2455. * we haven't yet exited the RCU idle mode. Do it here manually until
  2456. * we find a better solution.
  2457. *
  2458. * NB: There are buggy callers of this function. Ideally we
  2459. * should warn if prev_state != CONTEXT_USER, but that will trigger
  2460. * too frequently to make sense yet.
  2461. */
  2462. enum ctx_state prev_state = exception_enter();
  2463. schedule();
  2464. exception_exit(prev_state);
  2465. }
  2466. #endif
  2467. /**
  2468. * schedule_preempt_disabled - called with preemption disabled
  2469. *
  2470. * Returns with preemption disabled. Note: preempt_count must be 1
  2471. */
  2472. void __sched schedule_preempt_disabled(void)
  2473. {
  2474. sched_preempt_enable_no_resched();
  2475. schedule();
  2476. preempt_disable();
  2477. }
  2478. static void __sched notrace preempt_schedule_common(void)
  2479. {
  2480. do {
  2481. preempt_active_enter();
  2482. __schedule();
  2483. preempt_active_exit();
  2484. /*
  2485. * Check again in case we missed a preemption opportunity
  2486. * between schedule and now.
  2487. */
  2488. } while (need_resched());
  2489. }
  2490. #ifdef CONFIG_PREEMPT
  2491. /*
  2492. * this is the entry point to schedule() from in-kernel preemption
  2493. * off of preempt_enable. Kernel preemptions off return from interrupt
  2494. * occur there and call schedule directly.
  2495. */
  2496. asmlinkage __visible void __sched notrace preempt_schedule(void)
  2497. {
  2498. /*
  2499. * If there is a non-zero preempt_count or interrupts are disabled,
  2500. * we do not want to preempt the current task. Just return..
  2501. */
  2502. if (likely(!preemptible()))
  2503. return;
  2504. preempt_schedule_common();
  2505. }
  2506. NOKPROBE_SYMBOL(preempt_schedule);
  2507. EXPORT_SYMBOL(preempt_schedule);
  2508. /**
  2509. * preempt_schedule_notrace - preempt_schedule called by tracing
  2510. *
  2511. * The tracing infrastructure uses preempt_enable_notrace to prevent
  2512. * recursion and tracing preempt enabling caused by the tracing
  2513. * infrastructure itself. But as tracing can happen in areas coming
  2514. * from userspace or just about to enter userspace, a preempt enable
  2515. * can occur before user_exit() is called. This will cause the scheduler
  2516. * to be called when the system is still in usermode.
  2517. *
  2518. * To prevent this, the preempt_enable_notrace will use this function
  2519. * instead of preempt_schedule() to exit user context if needed before
  2520. * calling the scheduler.
  2521. */
  2522. asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
  2523. {
  2524. enum ctx_state prev_ctx;
  2525. if (likely(!preemptible()))
  2526. return;
  2527. do {
  2528. /*
  2529. * Use raw __prempt_count() ops that don't call function.
  2530. * We can't call functions before disabling preemption which
  2531. * disarm preemption tracing recursions.
  2532. */
  2533. __preempt_count_add(PREEMPT_ACTIVE + PREEMPT_DISABLE_OFFSET);
  2534. barrier();
  2535. /*
  2536. * Needs preempt disabled in case user_exit() is traced
  2537. * and the tracer calls preempt_enable_notrace() causing
  2538. * an infinite recursion.
  2539. */
  2540. prev_ctx = exception_enter();
  2541. __schedule();
  2542. exception_exit(prev_ctx);
  2543. barrier();
  2544. __preempt_count_sub(PREEMPT_ACTIVE + PREEMPT_DISABLE_OFFSET);
  2545. } while (need_resched());
  2546. }
  2547. EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
  2548. #endif /* CONFIG_PREEMPT */
  2549. /*
  2550. * this is the entry point to schedule() from kernel preemption
  2551. * off of irq context.
  2552. * Note, that this is called and return with irqs disabled. This will
  2553. * protect us against recursive calling from irq.
  2554. */
  2555. asmlinkage __visible void __sched preempt_schedule_irq(void)
  2556. {
  2557. enum ctx_state prev_state;
  2558. /* Catch callers which need to be fixed */
  2559. BUG_ON(preempt_count() || !irqs_disabled());
  2560. prev_state = exception_enter();
  2561. do {
  2562. preempt_active_enter();
  2563. local_irq_enable();
  2564. __schedule();
  2565. local_irq_disable();
  2566. preempt_active_exit();
  2567. } while (need_resched());
  2568. exception_exit(prev_state);
  2569. }
  2570. int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
  2571. void *key)
  2572. {
  2573. return try_to_wake_up(curr->private, mode, wake_flags);
  2574. }
  2575. EXPORT_SYMBOL(default_wake_function);
  2576. #ifdef CONFIG_RT_MUTEXES
  2577. /*
  2578. * rt_mutex_setprio - set the current priority of a task
  2579. * @p: task
  2580. * @prio: prio value (kernel-internal form)
  2581. *
  2582. * This function changes the 'effective' priority of a task. It does
  2583. * not touch ->normal_prio like __setscheduler().
  2584. *
  2585. * Used by the rt_mutex code to implement priority inheritance
  2586. * logic. Call site only calls if the priority of the task changed.
  2587. */
  2588. void rt_mutex_setprio(struct task_struct *p, int prio)
  2589. {
  2590. int oldprio, queued, running, enqueue_flag = 0;
  2591. struct rq *rq;
  2592. const struct sched_class *prev_class;
  2593. BUG_ON(prio > MAX_PRIO);
  2594. rq = __task_rq_lock(p);
  2595. /*
  2596. * Idle task boosting is a nono in general. There is one
  2597. * exception, when PREEMPT_RT and NOHZ is active:
  2598. *
  2599. * The idle task calls get_next_timer_interrupt() and holds
  2600. * the timer wheel base->lock on the CPU and another CPU wants
  2601. * to access the timer (probably to cancel it). We can safely
  2602. * ignore the boosting request, as the idle CPU runs this code
  2603. * with interrupts disabled and will complete the lock
  2604. * protected section without being interrupted. So there is no
  2605. * real need to boost.
  2606. */
  2607. if (unlikely(p == rq->idle)) {
  2608. WARN_ON(p != rq->curr);
  2609. WARN_ON(p->pi_blocked_on);
  2610. goto out_unlock;
  2611. }
  2612. trace_sched_pi_setprio(p, prio);
  2613. oldprio = p->prio;
  2614. prev_class = p->sched_class;
  2615. queued = task_on_rq_queued(p);
  2616. running = task_current(rq, p);
  2617. if (queued)
  2618. dequeue_task(rq, p, 0);
  2619. if (running)
  2620. put_prev_task(rq, p);
  2621. /*
  2622. * Boosting condition are:
  2623. * 1. -rt task is running and holds mutex A
  2624. * --> -dl task blocks on mutex A
  2625. *
  2626. * 2. -dl task is running and holds mutex A
  2627. * --> -dl task blocks on mutex A and could preempt the
  2628. * running task
  2629. */
  2630. if (dl_prio(prio)) {
  2631. struct task_struct *pi_task = rt_mutex_get_top_task(p);
  2632. if (!dl_prio(p->normal_prio) ||
  2633. (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
  2634. p->dl.dl_boosted = 1;
  2635. p->dl.dl_throttled = 0;
  2636. enqueue_flag = ENQUEUE_REPLENISH;
  2637. } else
  2638. p->dl.dl_boosted = 0;
  2639. p->sched_class = &dl_sched_class;
  2640. } else if (rt_prio(prio)) {
  2641. if (dl_prio(oldprio))
  2642. p->dl.dl_boosted = 0;
  2643. if (oldprio < prio)
  2644. enqueue_flag = ENQUEUE_HEAD;
  2645. p->sched_class = &rt_sched_class;
  2646. } else {
  2647. if (dl_prio(oldprio))
  2648. p->dl.dl_boosted = 0;
  2649. if (rt_prio(oldprio))
  2650. p->rt.timeout = 0;
  2651. p->sched_class = &fair_sched_class;
  2652. }
  2653. p->prio = prio;
  2654. if (running)
  2655. p->sched_class->set_curr_task(rq);
  2656. if (queued)
  2657. enqueue_task(rq, p, enqueue_flag);
  2658. check_class_changed(rq, p, prev_class, oldprio);
  2659. out_unlock:
  2660. __task_rq_unlock(rq);
  2661. }
  2662. #endif
  2663. void set_user_nice(struct task_struct *p, long nice)
  2664. {
  2665. int old_prio, delta, queued;
  2666. unsigned long flags;
  2667. struct rq *rq;
  2668. if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
  2669. return;
  2670. /*
  2671. * We have to be careful, if called from sys_setpriority(),
  2672. * the task might be in the middle of scheduling on another CPU.
  2673. */
  2674. rq = task_rq_lock(p, &flags);
  2675. /*
  2676. * The RT priorities are set via sched_setscheduler(), but we still
  2677. * allow the 'normal' nice value to be set - but as expected
  2678. * it wont have any effect on scheduling until the task is
  2679. * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
  2680. */
  2681. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  2682. p->static_prio = NICE_TO_PRIO(nice);
  2683. goto out_unlock;
  2684. }
  2685. queued = task_on_rq_queued(p);
  2686. if (queued)
  2687. dequeue_task(rq, p, 0);
  2688. p->static_prio = NICE_TO_PRIO(nice);
  2689. set_load_weight(p);
  2690. old_prio = p->prio;
  2691. p->prio = effective_prio(p);
  2692. delta = p->prio - old_prio;
  2693. if (queued) {
  2694. enqueue_task(rq, p, 0);
  2695. /*
  2696. * If the task increased its priority or is running and
  2697. * lowered its priority, then reschedule its CPU:
  2698. */
  2699. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  2700. resched_curr(rq);
  2701. }
  2702. out_unlock:
  2703. task_rq_unlock(rq, p, &flags);
  2704. }
  2705. EXPORT_SYMBOL(set_user_nice);
  2706. /*
  2707. * can_nice - check if a task can reduce its nice value
  2708. * @p: task
  2709. * @nice: nice value
  2710. */
  2711. int can_nice(const struct task_struct *p, const int nice)
  2712. {
  2713. /* convert nice value [19,-20] to rlimit style value [1,40] */
  2714. int nice_rlim = nice_to_rlimit(nice);
  2715. return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
  2716. capable(CAP_SYS_NICE));
  2717. }
  2718. #ifdef __ARCH_WANT_SYS_NICE
  2719. /*
  2720. * sys_nice - change the priority of the current process.
  2721. * @increment: priority increment
  2722. *
  2723. * sys_setpriority is a more generic, but much slower function that
  2724. * does similar things.
  2725. */
  2726. SYSCALL_DEFINE1(nice, int, increment)
  2727. {
  2728. long nice, retval;
  2729. /*
  2730. * Setpriority might change our priority at the same moment.
  2731. * We don't have to worry. Conceptually one call occurs first
  2732. * and we have a single winner.
  2733. */
  2734. increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
  2735. nice = task_nice(current) + increment;
  2736. nice = clamp_val(nice, MIN_NICE, MAX_NICE);
  2737. if (increment < 0 && !can_nice(current, nice))
  2738. return -EPERM;
  2739. retval = security_task_setnice(current, nice);
  2740. if (retval)
  2741. return retval;
  2742. set_user_nice(current, nice);
  2743. return 0;
  2744. }
  2745. #endif
  2746. /**
  2747. * task_prio - return the priority value of a given task.
  2748. * @p: the task in question.
  2749. *
  2750. * Return: The priority value as seen by users in /proc.
  2751. * RT tasks are offset by -200. Normal tasks are centered
  2752. * around 0, value goes from -16 to +15.
  2753. */
  2754. int task_prio(const struct task_struct *p)
  2755. {
  2756. return p->prio - MAX_RT_PRIO;
  2757. }
  2758. /**
  2759. * idle_cpu - is a given cpu idle currently?
  2760. * @cpu: the processor in question.
  2761. *
  2762. * Return: 1 if the CPU is currently idle. 0 otherwise.
  2763. */
  2764. int idle_cpu(int cpu)
  2765. {
  2766. struct rq *rq = cpu_rq(cpu);
  2767. if (rq->curr != rq->idle)
  2768. return 0;
  2769. if (rq->nr_running)
  2770. return 0;
  2771. #ifdef CONFIG_SMP
  2772. if (!llist_empty(&rq->wake_list))
  2773. return 0;
  2774. #endif
  2775. return 1;
  2776. }
  2777. /**
  2778. * idle_task - return the idle task for a given cpu.
  2779. * @cpu: the processor in question.
  2780. *
  2781. * Return: The idle task for the cpu @cpu.
  2782. */
  2783. struct task_struct *idle_task(int cpu)
  2784. {
  2785. return cpu_rq(cpu)->idle;
  2786. }
  2787. /**
  2788. * find_process_by_pid - find a process with a matching PID value.
  2789. * @pid: the pid in question.
  2790. *
  2791. * The task of @pid, if found. %NULL otherwise.
  2792. */
  2793. static struct task_struct *find_process_by_pid(pid_t pid)
  2794. {
  2795. return pid ? find_task_by_vpid(pid) : current;
  2796. }
  2797. /*
  2798. * This function initializes the sched_dl_entity of a newly becoming
  2799. * SCHED_DEADLINE task.
  2800. *
  2801. * Only the static values are considered here, the actual runtime and the
  2802. * absolute deadline will be properly calculated when the task is enqueued
  2803. * for the first time with its new policy.
  2804. */
  2805. static void
  2806. __setparam_dl(struct task_struct *p, const struct sched_attr *attr)
  2807. {
  2808. struct sched_dl_entity *dl_se = &p->dl;
  2809. dl_se->dl_runtime = attr->sched_runtime;
  2810. dl_se->dl_deadline = attr->sched_deadline;
  2811. dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline;
  2812. dl_se->flags = attr->sched_flags;
  2813. dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime);
  2814. /*
  2815. * Changing the parameters of a task is 'tricky' and we're not doing
  2816. * the correct thing -- also see task_dead_dl() and switched_from_dl().
  2817. *
  2818. * What we SHOULD do is delay the bandwidth release until the 0-lag
  2819. * point. This would include retaining the task_struct until that time
  2820. * and change dl_overflow() to not immediately decrement the current
  2821. * amount.
  2822. *
  2823. * Instead we retain the current runtime/deadline and let the new
  2824. * parameters take effect after the current reservation period lapses.
  2825. * This is safe (albeit pessimistic) because the 0-lag point is always
  2826. * before the current scheduling deadline.
  2827. *
  2828. * We can still have temporary overloads because we do not delay the
  2829. * change in bandwidth until that time; so admission control is
  2830. * not on the safe side. It does however guarantee tasks will never
  2831. * consume more than promised.
  2832. */
  2833. }
  2834. /*
  2835. * sched_setparam() passes in -1 for its policy, to let the functions
  2836. * it calls know not to change it.
  2837. */
  2838. #define SETPARAM_POLICY -1
  2839. static void __setscheduler_params(struct task_struct *p,
  2840. const struct sched_attr *attr)
  2841. {
  2842. int policy = attr->sched_policy;
  2843. if (policy == SETPARAM_POLICY)
  2844. policy = p->policy;
  2845. p->policy = policy;
  2846. if (dl_policy(policy))
  2847. __setparam_dl(p, attr);
  2848. else if (fair_policy(policy))
  2849. p->static_prio = NICE_TO_PRIO(attr->sched_nice);
  2850. /*
  2851. * __sched_setscheduler() ensures attr->sched_priority == 0 when
  2852. * !rt_policy. Always setting this ensures that things like
  2853. * getparam()/getattr() don't report silly values for !rt tasks.
  2854. */
  2855. p->rt_priority = attr->sched_priority;
  2856. p->normal_prio = normal_prio(p);
  2857. set_load_weight(p);
  2858. }
  2859. /* Actually do priority change: must hold pi & rq lock. */
  2860. static void __setscheduler(struct rq *rq, struct task_struct *p,
  2861. const struct sched_attr *attr, bool keep_boost)
  2862. {
  2863. __setscheduler_params(p, attr);
  2864. /*
  2865. * Keep a potential priority boosting if called from
  2866. * sched_setscheduler().
  2867. */
  2868. if (keep_boost)
  2869. p->prio = rt_mutex_get_effective_prio(p, normal_prio(p));
  2870. else
  2871. p->prio = normal_prio(p);
  2872. if (dl_prio(p->prio))
  2873. p->sched_class = &dl_sched_class;
  2874. else if (rt_prio(p->prio))
  2875. p->sched_class = &rt_sched_class;
  2876. else
  2877. p->sched_class = &fair_sched_class;
  2878. }
  2879. static void
  2880. __getparam_dl(struct task_struct *p, struct sched_attr *attr)
  2881. {
  2882. struct sched_dl_entity *dl_se = &p->dl;
  2883. attr->sched_priority = p->rt_priority;
  2884. attr->sched_runtime = dl_se->dl_runtime;
  2885. attr->sched_deadline = dl_se->dl_deadline;
  2886. attr->sched_period = dl_se->dl_period;
  2887. attr->sched_flags = dl_se->flags;
  2888. }
  2889. /*
  2890. * This function validates the new parameters of a -deadline task.
  2891. * We ask for the deadline not being zero, and greater or equal
  2892. * than the runtime, as well as the period of being zero or
  2893. * greater than deadline. Furthermore, we have to be sure that
  2894. * user parameters are above the internal resolution of 1us (we
  2895. * check sched_runtime only since it is always the smaller one) and
  2896. * below 2^63 ns (we have to check both sched_deadline and
  2897. * sched_period, as the latter can be zero).
  2898. */
  2899. static bool
  2900. __checkparam_dl(const struct sched_attr *attr)
  2901. {
  2902. /* deadline != 0 */
  2903. if (attr->sched_deadline == 0)
  2904. return false;
  2905. /*
  2906. * Since we truncate DL_SCALE bits, make sure we're at least
  2907. * that big.
  2908. */
  2909. if (attr->sched_runtime < (1ULL << DL_SCALE))
  2910. return false;
  2911. /*
  2912. * Since we use the MSB for wrap-around and sign issues, make
  2913. * sure it's not set (mind that period can be equal to zero).
  2914. */
  2915. if (attr->sched_deadline & (1ULL << 63) ||
  2916. attr->sched_period & (1ULL << 63))
  2917. return false;
  2918. /* runtime <= deadline <= period (if period != 0) */
  2919. if ((attr->sched_period != 0 &&
  2920. attr->sched_period < attr->sched_deadline) ||
  2921. attr->sched_deadline < attr->sched_runtime)
  2922. return false;
  2923. return true;
  2924. }
  2925. /*
  2926. * check the target process has a UID that matches the current process's
  2927. */
  2928. static bool check_same_owner(struct task_struct *p)
  2929. {
  2930. const struct cred *cred = current_cred(), *pcred;
  2931. bool match;
  2932. rcu_read_lock();
  2933. pcred = __task_cred(p);
  2934. match = (uid_eq(cred->euid, pcred->euid) ||
  2935. uid_eq(cred->euid, pcred->uid));
  2936. rcu_read_unlock();
  2937. return match;
  2938. }
  2939. static bool dl_param_changed(struct task_struct *p,
  2940. const struct sched_attr *attr)
  2941. {
  2942. struct sched_dl_entity *dl_se = &p->dl;
  2943. if (dl_se->dl_runtime != attr->sched_runtime ||
  2944. dl_se->dl_deadline != attr->sched_deadline ||
  2945. dl_se->dl_period != attr->sched_period ||
  2946. dl_se->flags != attr->sched_flags)
  2947. return true;
  2948. return false;
  2949. }
  2950. static int __sched_setscheduler(struct task_struct *p,
  2951. const struct sched_attr *attr,
  2952. bool user)
  2953. {
  2954. int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
  2955. MAX_RT_PRIO - 1 - attr->sched_priority;
  2956. int retval, oldprio, oldpolicy = -1, queued, running;
  2957. int new_effective_prio, policy = attr->sched_policy;
  2958. unsigned long flags;
  2959. const struct sched_class *prev_class;
  2960. struct rq *rq;
  2961. int reset_on_fork;
  2962. /* may grab non-irq protected spin_locks */
  2963. BUG_ON(in_interrupt());
  2964. recheck:
  2965. /* double check policy once rq lock held */
  2966. if (policy < 0) {
  2967. reset_on_fork = p->sched_reset_on_fork;
  2968. policy = oldpolicy = p->policy;
  2969. } else {
  2970. reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
  2971. if (policy != SCHED_DEADLINE &&
  2972. policy != SCHED_FIFO && policy != SCHED_RR &&
  2973. policy != SCHED_NORMAL && policy != SCHED_BATCH &&
  2974. policy != SCHED_IDLE)
  2975. return -EINVAL;
  2976. }
  2977. if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK))
  2978. return -EINVAL;
  2979. /*
  2980. * Valid priorities for SCHED_FIFO and SCHED_RR are
  2981. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
  2982. * SCHED_BATCH and SCHED_IDLE is 0.
  2983. */
  2984. if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
  2985. (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
  2986. return -EINVAL;
  2987. if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
  2988. (rt_policy(policy) != (attr->sched_priority != 0)))
  2989. return -EINVAL;
  2990. /*
  2991. * Allow unprivileged RT tasks to decrease priority:
  2992. */
  2993. if (user && !capable(CAP_SYS_NICE)) {
  2994. if (fair_policy(policy)) {
  2995. if (attr->sched_nice < task_nice(p) &&
  2996. !can_nice(p, attr->sched_nice))
  2997. return -EPERM;
  2998. }
  2999. if (rt_policy(policy)) {
  3000. unsigned long rlim_rtprio =
  3001. task_rlimit(p, RLIMIT_RTPRIO);
  3002. /* can't set/change the rt policy */
  3003. if (policy != p->policy && !rlim_rtprio)
  3004. return -EPERM;
  3005. /* can't increase priority */
  3006. if (attr->sched_priority > p->rt_priority &&
  3007. attr->sched_priority > rlim_rtprio)
  3008. return -EPERM;
  3009. }
  3010. /*
  3011. * Can't set/change SCHED_DEADLINE policy at all for now
  3012. * (safest behavior); in the future we would like to allow
  3013. * unprivileged DL tasks to increase their relative deadline
  3014. * or reduce their runtime (both ways reducing utilization)
  3015. */
  3016. if (dl_policy(policy))
  3017. return -EPERM;
  3018. /*
  3019. * Treat SCHED_IDLE as nice 20. Only allow a switch to
  3020. * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
  3021. */
  3022. if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) {
  3023. if (!can_nice(p, task_nice(p)))
  3024. return -EPERM;
  3025. }
  3026. /* can't change other user's priorities */
  3027. if (!check_same_owner(p))
  3028. return -EPERM;
  3029. /* Normal users shall not reset the sched_reset_on_fork flag */
  3030. if (p->sched_reset_on_fork && !reset_on_fork)
  3031. return -EPERM;
  3032. }
  3033. if (user) {
  3034. retval = security_task_setscheduler(p);
  3035. if (retval)
  3036. return retval;
  3037. }
  3038. /*
  3039. * make sure no PI-waiters arrive (or leave) while we are
  3040. * changing the priority of the task:
  3041. *
  3042. * To be able to change p->policy safely, the appropriate
  3043. * runqueue lock must be held.
  3044. */
  3045. rq = task_rq_lock(p, &flags);
  3046. /*
  3047. * Changing the policy of the stop threads its a very bad idea
  3048. */
  3049. if (p == rq->stop) {
  3050. task_rq_unlock(rq, p, &flags);
  3051. return -EINVAL;
  3052. }
  3053. /*
  3054. * If not changing anything there's no need to proceed further,
  3055. * but store a possible modification of reset_on_fork.
  3056. */
  3057. if (unlikely(policy == p->policy)) {
  3058. if (fair_policy(policy) && attr->sched_nice != task_nice(p))
  3059. goto change;
  3060. if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
  3061. goto change;
  3062. if (dl_policy(policy) && dl_param_changed(p, attr))
  3063. goto change;
  3064. p->sched_reset_on_fork = reset_on_fork;
  3065. task_rq_unlock(rq, p, &flags);
  3066. return 0;
  3067. }
  3068. change:
  3069. if (user) {
  3070. #ifdef CONFIG_RT_GROUP_SCHED
  3071. /*
  3072. * Do not allow realtime tasks into groups that have no runtime
  3073. * assigned.
  3074. */
  3075. if (rt_bandwidth_enabled() && rt_policy(policy) &&
  3076. task_group(p)->rt_bandwidth.rt_runtime == 0 &&
  3077. !task_group_is_autogroup(task_group(p))) {
  3078. task_rq_unlock(rq, p, &flags);
  3079. return -EPERM;
  3080. }
  3081. #endif
  3082. #ifdef CONFIG_SMP
  3083. if (dl_bandwidth_enabled() && dl_policy(policy)) {
  3084. cpumask_t *span = rq->rd->span;
  3085. /*
  3086. * Don't allow tasks with an affinity mask smaller than
  3087. * the entire root_domain to become SCHED_DEADLINE. We
  3088. * will also fail if there's no bandwidth available.
  3089. */
  3090. if (!cpumask_subset(span, &p->cpus_allowed) ||
  3091. rq->rd->dl_bw.bw == 0) {
  3092. task_rq_unlock(rq, p, &flags);
  3093. return -EPERM;
  3094. }
  3095. }
  3096. #endif
  3097. }
  3098. /* recheck policy now with rq lock held */
  3099. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3100. policy = oldpolicy = -1;
  3101. task_rq_unlock(rq, p, &flags);
  3102. goto recheck;
  3103. }
  3104. /*
  3105. * If setscheduling to SCHED_DEADLINE (or changing the parameters
  3106. * of a SCHED_DEADLINE task) we need to check if enough bandwidth
  3107. * is available.
  3108. */
  3109. if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) {
  3110. task_rq_unlock(rq, p, &flags);
  3111. return -EBUSY;
  3112. }
  3113. p->sched_reset_on_fork = reset_on_fork;
  3114. oldprio = p->prio;
  3115. /*
  3116. * Take priority boosted tasks into account. If the new
  3117. * effective priority is unchanged, we just store the new
  3118. * normal parameters and do not touch the scheduler class and
  3119. * the runqueue. This will be done when the task deboost
  3120. * itself.
  3121. */
  3122. new_effective_prio = rt_mutex_get_effective_prio(p, newprio);
  3123. if (new_effective_prio == oldprio) {
  3124. __setscheduler_params(p, attr);
  3125. task_rq_unlock(rq, p, &flags);
  3126. return 0;
  3127. }
  3128. queued = task_on_rq_queued(p);
  3129. running = task_current(rq, p);
  3130. if (queued)
  3131. dequeue_task(rq, p, 0);
  3132. if (running)
  3133. put_prev_task(rq, p);
  3134. prev_class = p->sched_class;
  3135. __setscheduler(rq, p, attr, true);
  3136. if (running)
  3137. p->sched_class->set_curr_task(rq);
  3138. if (queued) {
  3139. /*
  3140. * We enqueue to tail when the priority of a task is
  3141. * increased (user space view).
  3142. */
  3143. enqueue_task(rq, p, oldprio <= p->prio ? ENQUEUE_HEAD : 0);
  3144. }
  3145. check_class_changed(rq, p, prev_class, oldprio);
  3146. task_rq_unlock(rq, p, &flags);
  3147. rt_mutex_adjust_pi(p);
  3148. return 0;
  3149. }
  3150. static int _sched_setscheduler(struct task_struct *p, int policy,
  3151. const struct sched_param *param, bool check)
  3152. {
  3153. struct sched_attr attr = {
  3154. .sched_policy = policy,
  3155. .sched_priority = param->sched_priority,
  3156. .sched_nice = PRIO_TO_NICE(p->static_prio),
  3157. };
  3158. /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
  3159. if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
  3160. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  3161. policy &= ~SCHED_RESET_ON_FORK;
  3162. attr.sched_policy = policy;
  3163. }
  3164. return __sched_setscheduler(p, &attr, check);
  3165. }
  3166. /**
  3167. * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
  3168. * @p: the task in question.
  3169. * @policy: new policy.
  3170. * @param: structure containing the new RT priority.
  3171. *
  3172. * Return: 0 on success. An error code otherwise.
  3173. *
  3174. * NOTE that the task may be already dead.
  3175. */
  3176. int sched_setscheduler(struct task_struct *p, int policy,
  3177. const struct sched_param *param)
  3178. {
  3179. return _sched_setscheduler(p, policy, param, true);
  3180. }
  3181. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3182. int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
  3183. {
  3184. return __sched_setscheduler(p, attr, true);
  3185. }
  3186. EXPORT_SYMBOL_GPL(sched_setattr);
  3187. /**
  3188. * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
  3189. * @p: the task in question.
  3190. * @policy: new policy.
  3191. * @param: structure containing the new RT priority.
  3192. *
  3193. * Just like sched_setscheduler, only don't bother checking if the
  3194. * current context has permission. For example, this is needed in
  3195. * stop_machine(): we create temporary high priority worker threads,
  3196. * but our caller might not have that capability.
  3197. *
  3198. * Return: 0 on success. An error code otherwise.
  3199. */
  3200. int sched_setscheduler_nocheck(struct task_struct *p, int policy,
  3201. const struct sched_param *param)
  3202. {
  3203. return _sched_setscheduler(p, policy, param, false);
  3204. }
  3205. static int
  3206. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3207. {
  3208. struct sched_param lparam;
  3209. struct task_struct *p;
  3210. int retval;
  3211. if (!param || pid < 0)
  3212. return -EINVAL;
  3213. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3214. return -EFAULT;
  3215. rcu_read_lock();
  3216. retval = -ESRCH;
  3217. p = find_process_by_pid(pid);
  3218. if (p != NULL)
  3219. retval = sched_setscheduler(p, policy, &lparam);
  3220. rcu_read_unlock();
  3221. return retval;
  3222. }
  3223. /*
  3224. * Mimics kernel/events/core.c perf_copy_attr().
  3225. */
  3226. static int sched_copy_attr(struct sched_attr __user *uattr,
  3227. struct sched_attr *attr)
  3228. {
  3229. u32 size;
  3230. int ret;
  3231. if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
  3232. return -EFAULT;
  3233. /*
  3234. * zero the full structure, so that a short copy will be nice.
  3235. */
  3236. memset(attr, 0, sizeof(*attr));
  3237. ret = get_user(size, &uattr->size);
  3238. if (ret)
  3239. return ret;
  3240. if (size > PAGE_SIZE) /* silly large */
  3241. goto err_size;
  3242. if (!size) /* abi compat */
  3243. size = SCHED_ATTR_SIZE_VER0;
  3244. if (size < SCHED_ATTR_SIZE_VER0)
  3245. goto err_size;
  3246. /*
  3247. * If we're handed a bigger struct than we know of,
  3248. * ensure all the unknown bits are 0 - i.e. new
  3249. * user-space does not rely on any kernel feature
  3250. * extensions we dont know about yet.
  3251. */
  3252. if (size > sizeof(*attr)) {
  3253. unsigned char __user *addr;
  3254. unsigned char __user *end;
  3255. unsigned char val;
  3256. addr = (void __user *)uattr + sizeof(*attr);
  3257. end = (void __user *)uattr + size;
  3258. for (; addr < end; addr++) {
  3259. ret = get_user(val, addr);
  3260. if (ret)
  3261. return ret;
  3262. if (val)
  3263. goto err_size;
  3264. }
  3265. size = sizeof(*attr);
  3266. }
  3267. ret = copy_from_user(attr, uattr, size);
  3268. if (ret)
  3269. return -EFAULT;
  3270. /*
  3271. * XXX: do we want to be lenient like existing syscalls; or do we want
  3272. * to be strict and return an error on out-of-bounds values?
  3273. */
  3274. attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
  3275. return 0;
  3276. err_size:
  3277. put_user(sizeof(*attr), &uattr->size);
  3278. return -E2BIG;
  3279. }
  3280. /**
  3281. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3282. * @pid: the pid in question.
  3283. * @policy: new policy.
  3284. * @param: structure containing the new RT priority.
  3285. *
  3286. * Return: 0 on success. An error code otherwise.
  3287. */
  3288. SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
  3289. struct sched_param __user *, param)
  3290. {
  3291. /* negative values for policy are not valid */
  3292. if (policy < 0)
  3293. return -EINVAL;
  3294. return do_sched_setscheduler(pid, policy, param);
  3295. }
  3296. /**
  3297. * sys_sched_setparam - set/change the RT priority of a thread
  3298. * @pid: the pid in question.
  3299. * @param: structure containing the new RT priority.
  3300. *
  3301. * Return: 0 on success. An error code otherwise.
  3302. */
  3303. SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
  3304. {
  3305. return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
  3306. }
  3307. /**
  3308. * sys_sched_setattr - same as above, but with extended sched_attr
  3309. * @pid: the pid in question.
  3310. * @uattr: structure containing the extended parameters.
  3311. * @flags: for future extension.
  3312. */
  3313. SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
  3314. unsigned int, flags)
  3315. {
  3316. struct sched_attr attr;
  3317. struct task_struct *p;
  3318. int retval;
  3319. if (!uattr || pid < 0 || flags)
  3320. return -EINVAL;
  3321. retval = sched_copy_attr(uattr, &attr);
  3322. if (retval)
  3323. return retval;
  3324. if ((int)attr.sched_policy < 0)
  3325. return -EINVAL;
  3326. rcu_read_lock();
  3327. retval = -ESRCH;
  3328. p = find_process_by_pid(pid);
  3329. if (p != NULL)
  3330. retval = sched_setattr(p, &attr);
  3331. rcu_read_unlock();
  3332. return retval;
  3333. }
  3334. /**
  3335. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3336. * @pid: the pid in question.
  3337. *
  3338. * Return: On success, the policy of the thread. Otherwise, a negative error
  3339. * code.
  3340. */
  3341. SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
  3342. {
  3343. struct task_struct *p;
  3344. int retval;
  3345. if (pid < 0)
  3346. return -EINVAL;
  3347. retval = -ESRCH;
  3348. rcu_read_lock();
  3349. p = find_process_by_pid(pid);
  3350. if (p) {
  3351. retval = security_task_getscheduler(p);
  3352. if (!retval)
  3353. retval = p->policy
  3354. | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
  3355. }
  3356. rcu_read_unlock();
  3357. return retval;
  3358. }
  3359. /**
  3360. * sys_sched_getparam - get the RT priority of a thread
  3361. * @pid: the pid in question.
  3362. * @param: structure containing the RT priority.
  3363. *
  3364. * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
  3365. * code.
  3366. */
  3367. SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
  3368. {
  3369. struct sched_param lp = { .sched_priority = 0 };
  3370. struct task_struct *p;
  3371. int retval;
  3372. if (!param || pid < 0)
  3373. return -EINVAL;
  3374. rcu_read_lock();
  3375. p = find_process_by_pid(pid);
  3376. retval = -ESRCH;
  3377. if (!p)
  3378. goto out_unlock;
  3379. retval = security_task_getscheduler(p);
  3380. if (retval)
  3381. goto out_unlock;
  3382. if (task_has_rt_policy(p))
  3383. lp.sched_priority = p->rt_priority;
  3384. rcu_read_unlock();
  3385. /*
  3386. * This one might sleep, we cannot do it with a spinlock held ...
  3387. */
  3388. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  3389. return retval;
  3390. out_unlock:
  3391. rcu_read_unlock();
  3392. return retval;
  3393. }
  3394. static int sched_read_attr(struct sched_attr __user *uattr,
  3395. struct sched_attr *attr,
  3396. unsigned int usize)
  3397. {
  3398. int ret;
  3399. if (!access_ok(VERIFY_WRITE, uattr, usize))
  3400. return -EFAULT;
  3401. /*
  3402. * If we're handed a smaller struct than we know of,
  3403. * ensure all the unknown bits are 0 - i.e. old
  3404. * user-space does not get uncomplete information.
  3405. */
  3406. if (usize < sizeof(*attr)) {
  3407. unsigned char *addr;
  3408. unsigned char *end;
  3409. addr = (void *)attr + usize;
  3410. end = (void *)attr + sizeof(*attr);
  3411. for (; addr < end; addr++) {
  3412. if (*addr)
  3413. return -EFBIG;
  3414. }
  3415. attr->size = usize;
  3416. }
  3417. ret = copy_to_user(uattr, attr, attr->size);
  3418. if (ret)
  3419. return -EFAULT;
  3420. return 0;
  3421. }
  3422. /**
  3423. * sys_sched_getattr - similar to sched_getparam, but with sched_attr
  3424. * @pid: the pid in question.
  3425. * @uattr: structure containing the extended parameters.
  3426. * @size: sizeof(attr) for fwd/bwd comp.
  3427. * @flags: for future extension.
  3428. */
  3429. SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
  3430. unsigned int, size, unsigned int, flags)
  3431. {
  3432. struct sched_attr attr = {
  3433. .size = sizeof(struct sched_attr),
  3434. };
  3435. struct task_struct *p;
  3436. int retval;
  3437. if (!uattr || pid < 0 || size > PAGE_SIZE ||
  3438. size < SCHED_ATTR_SIZE_VER0 || flags)
  3439. return -EINVAL;
  3440. rcu_read_lock();
  3441. p = find_process_by_pid(pid);
  3442. retval = -ESRCH;
  3443. if (!p)
  3444. goto out_unlock;
  3445. retval = security_task_getscheduler(p);
  3446. if (retval)
  3447. goto out_unlock;
  3448. attr.sched_policy = p->policy;
  3449. if (p->sched_reset_on_fork)
  3450. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  3451. if (task_has_dl_policy(p))
  3452. __getparam_dl(p, &attr);
  3453. else if (task_has_rt_policy(p))
  3454. attr.sched_priority = p->rt_priority;
  3455. else
  3456. attr.sched_nice = task_nice(p);
  3457. rcu_read_unlock();
  3458. retval = sched_read_attr(uattr, &attr, size);
  3459. return retval;
  3460. out_unlock:
  3461. rcu_read_unlock();
  3462. return retval;
  3463. }
  3464. long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
  3465. {
  3466. cpumask_var_t cpus_allowed, new_mask;
  3467. struct task_struct *p;
  3468. int retval;
  3469. rcu_read_lock();
  3470. p = find_process_by_pid(pid);
  3471. if (!p) {
  3472. rcu_read_unlock();
  3473. return -ESRCH;
  3474. }
  3475. /* Prevent p going away */
  3476. get_task_struct(p);
  3477. rcu_read_unlock();
  3478. if (p->flags & PF_NO_SETAFFINITY) {
  3479. retval = -EINVAL;
  3480. goto out_put_task;
  3481. }
  3482. if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
  3483. retval = -ENOMEM;
  3484. goto out_put_task;
  3485. }
  3486. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
  3487. retval = -ENOMEM;
  3488. goto out_free_cpus_allowed;
  3489. }
  3490. retval = -EPERM;
  3491. if (!check_same_owner(p)) {
  3492. rcu_read_lock();
  3493. if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
  3494. rcu_read_unlock();
  3495. goto out_free_new_mask;
  3496. }
  3497. rcu_read_unlock();
  3498. }
  3499. retval = security_task_setscheduler(p);
  3500. if (retval)
  3501. goto out_free_new_mask;
  3502. cpuset_cpus_allowed(p, cpus_allowed);
  3503. cpumask_and(new_mask, in_mask, cpus_allowed);
  3504. /*
  3505. * Since bandwidth control happens on root_domain basis,
  3506. * if admission test is enabled, we only admit -deadline
  3507. * tasks allowed to run on all the CPUs in the task's
  3508. * root_domain.
  3509. */
  3510. #ifdef CONFIG_SMP
  3511. if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
  3512. rcu_read_lock();
  3513. if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
  3514. retval = -EBUSY;
  3515. rcu_read_unlock();
  3516. goto out_free_new_mask;
  3517. }
  3518. rcu_read_unlock();
  3519. }
  3520. #endif
  3521. again:
  3522. retval = set_cpus_allowed_ptr(p, new_mask);
  3523. if (!retval) {
  3524. cpuset_cpus_allowed(p, cpus_allowed);
  3525. if (!cpumask_subset(new_mask, cpus_allowed)) {
  3526. /*
  3527. * We must have raced with a concurrent cpuset
  3528. * update. Just reset the cpus_allowed to the
  3529. * cpuset's cpus_allowed
  3530. */
  3531. cpumask_copy(new_mask, cpus_allowed);
  3532. goto again;
  3533. }
  3534. }
  3535. out_free_new_mask:
  3536. free_cpumask_var(new_mask);
  3537. out_free_cpus_allowed:
  3538. free_cpumask_var(cpus_allowed);
  3539. out_put_task:
  3540. put_task_struct(p);
  3541. return retval;
  3542. }
  3543. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  3544. struct cpumask *new_mask)
  3545. {
  3546. if (len < cpumask_size())
  3547. cpumask_clear(new_mask);
  3548. else if (len > cpumask_size())
  3549. len = cpumask_size();
  3550. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  3551. }
  3552. /**
  3553. * sys_sched_setaffinity - set the cpu affinity of a process
  3554. * @pid: pid of the process
  3555. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3556. * @user_mask_ptr: user-space pointer to the new cpu mask
  3557. *
  3558. * Return: 0 on success. An error code otherwise.
  3559. */
  3560. SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
  3561. unsigned long __user *, user_mask_ptr)
  3562. {
  3563. cpumask_var_t new_mask;
  3564. int retval;
  3565. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
  3566. return -ENOMEM;
  3567. retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
  3568. if (retval == 0)
  3569. retval = sched_setaffinity(pid, new_mask);
  3570. free_cpumask_var(new_mask);
  3571. return retval;
  3572. }
  3573. long sched_getaffinity(pid_t pid, struct cpumask *mask)
  3574. {
  3575. struct task_struct *p;
  3576. unsigned long flags;
  3577. int retval;
  3578. rcu_read_lock();
  3579. retval = -ESRCH;
  3580. p = find_process_by_pid(pid);
  3581. if (!p)
  3582. goto out_unlock;
  3583. retval = security_task_getscheduler(p);
  3584. if (retval)
  3585. goto out_unlock;
  3586. raw_spin_lock_irqsave(&p->pi_lock, flags);
  3587. cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
  3588. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  3589. out_unlock:
  3590. rcu_read_unlock();
  3591. return retval;
  3592. }
  3593. /**
  3594. * sys_sched_getaffinity - get the cpu affinity of a process
  3595. * @pid: pid of the process
  3596. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3597. * @user_mask_ptr: user-space pointer to hold the current cpu mask
  3598. *
  3599. * Return: 0 on success. An error code otherwise.
  3600. */
  3601. SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
  3602. unsigned long __user *, user_mask_ptr)
  3603. {
  3604. int ret;
  3605. cpumask_var_t mask;
  3606. if ((len * BITS_PER_BYTE) < nr_cpu_ids)
  3607. return -EINVAL;
  3608. if (len & (sizeof(unsigned long)-1))
  3609. return -EINVAL;
  3610. if (!alloc_cpumask_var(&mask, GFP_KERNEL))
  3611. return -ENOMEM;
  3612. ret = sched_getaffinity(pid, mask);
  3613. if (ret == 0) {
  3614. size_t retlen = min_t(size_t, len, cpumask_size());
  3615. if (copy_to_user(user_mask_ptr, mask, retlen))
  3616. ret = -EFAULT;
  3617. else
  3618. ret = retlen;
  3619. }
  3620. free_cpumask_var(mask);
  3621. return ret;
  3622. }
  3623. /**
  3624. * sys_sched_yield - yield the current processor to other threads.
  3625. *
  3626. * This function yields the current CPU to other tasks. If there are no
  3627. * other threads running on this CPU then this function will return.
  3628. *
  3629. * Return: 0.
  3630. */
  3631. SYSCALL_DEFINE0(sched_yield)
  3632. {
  3633. struct rq *rq = this_rq_lock();
  3634. schedstat_inc(rq, yld_count);
  3635. current->sched_class->yield_task(rq);
  3636. /*
  3637. * Since we are going to call schedule() anyway, there's
  3638. * no need to preempt or enable interrupts:
  3639. */
  3640. __release(rq->lock);
  3641. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  3642. do_raw_spin_unlock(&rq->lock);
  3643. sched_preempt_enable_no_resched();
  3644. schedule();
  3645. return 0;
  3646. }
  3647. int __sched _cond_resched(void)
  3648. {
  3649. if (should_resched()) {
  3650. preempt_schedule_common();
  3651. return 1;
  3652. }
  3653. return 0;
  3654. }
  3655. EXPORT_SYMBOL(_cond_resched);
  3656. /*
  3657. * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
  3658. * call schedule, and on return reacquire the lock.
  3659. *
  3660. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  3661. * operations here to prevent schedule() from being called twice (once via
  3662. * spin_unlock(), once by hand).
  3663. */
  3664. int __cond_resched_lock(spinlock_t *lock)
  3665. {
  3666. int resched = should_resched();
  3667. int ret = 0;
  3668. lockdep_assert_held(lock);
  3669. if (spin_needbreak(lock) || resched) {
  3670. spin_unlock(lock);
  3671. if (resched)
  3672. preempt_schedule_common();
  3673. else
  3674. cpu_relax();
  3675. ret = 1;
  3676. spin_lock(lock);
  3677. }
  3678. return ret;
  3679. }
  3680. EXPORT_SYMBOL(__cond_resched_lock);
  3681. int __sched __cond_resched_softirq(void)
  3682. {
  3683. BUG_ON(!in_softirq());
  3684. if (should_resched()) {
  3685. local_bh_enable();
  3686. preempt_schedule_common();
  3687. local_bh_disable();
  3688. return 1;
  3689. }
  3690. return 0;
  3691. }
  3692. EXPORT_SYMBOL(__cond_resched_softirq);
  3693. /**
  3694. * yield - yield the current processor to other threads.
  3695. *
  3696. * Do not ever use this function, there's a 99% chance you're doing it wrong.
  3697. *
  3698. * The scheduler is at all times free to pick the calling task as the most
  3699. * eligible task to run, if removing the yield() call from your code breaks
  3700. * it, its already broken.
  3701. *
  3702. * Typical broken usage is:
  3703. *
  3704. * while (!event)
  3705. * yield();
  3706. *
  3707. * where one assumes that yield() will let 'the other' process run that will
  3708. * make event true. If the current task is a SCHED_FIFO task that will never
  3709. * happen. Never use yield() as a progress guarantee!!
  3710. *
  3711. * If you want to use yield() to wait for something, use wait_event().
  3712. * If you want to use yield() to be 'nice' for others, use cond_resched().
  3713. * If you still want to use yield(), do not!
  3714. */
  3715. void __sched yield(void)
  3716. {
  3717. set_current_state(TASK_RUNNING);
  3718. sys_sched_yield();
  3719. }
  3720. EXPORT_SYMBOL(yield);
  3721. /**
  3722. * yield_to - yield the current processor to another thread in
  3723. * your thread group, or accelerate that thread toward the
  3724. * processor it's on.
  3725. * @p: target task
  3726. * @preempt: whether task preemption is allowed or not
  3727. *
  3728. * It's the caller's job to ensure that the target task struct
  3729. * can't go away on us before we can do any checks.
  3730. *
  3731. * Return:
  3732. * true (>0) if we indeed boosted the target task.
  3733. * false (0) if we failed to boost the target.
  3734. * -ESRCH if there's no task to yield to.
  3735. */
  3736. int __sched yield_to(struct task_struct *p, bool preempt)
  3737. {
  3738. struct task_struct *curr = current;
  3739. struct rq *rq, *p_rq;
  3740. unsigned long flags;
  3741. int yielded = 0;
  3742. local_irq_save(flags);
  3743. rq = this_rq();
  3744. again:
  3745. p_rq = task_rq(p);
  3746. /*
  3747. * If we're the only runnable task on the rq and target rq also
  3748. * has only one task, there's absolutely no point in yielding.
  3749. */
  3750. if (rq->nr_running == 1 && p_rq->nr_running == 1) {
  3751. yielded = -ESRCH;
  3752. goto out_irq;
  3753. }
  3754. double_rq_lock(rq, p_rq);
  3755. if (task_rq(p) != p_rq) {
  3756. double_rq_unlock(rq, p_rq);
  3757. goto again;
  3758. }
  3759. if (!curr->sched_class->yield_to_task)
  3760. goto out_unlock;
  3761. if (curr->sched_class != p->sched_class)
  3762. goto out_unlock;
  3763. if (task_running(p_rq, p) || p->state)
  3764. goto out_unlock;
  3765. yielded = curr->sched_class->yield_to_task(rq, p, preempt);
  3766. if (yielded) {
  3767. schedstat_inc(rq, yld_count);
  3768. /*
  3769. * Make p's CPU reschedule; pick_next_entity takes care of
  3770. * fairness.
  3771. */
  3772. if (preempt && rq != p_rq)
  3773. resched_curr(p_rq);
  3774. }
  3775. out_unlock:
  3776. double_rq_unlock(rq, p_rq);
  3777. out_irq:
  3778. local_irq_restore(flags);
  3779. if (yielded > 0)
  3780. schedule();
  3781. return yielded;
  3782. }
  3783. EXPORT_SYMBOL_GPL(yield_to);
  3784. /*
  3785. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  3786. * that process accounting knows that this is a task in IO wait state.
  3787. */
  3788. long __sched io_schedule_timeout(long timeout)
  3789. {
  3790. int old_iowait = current->in_iowait;
  3791. struct rq *rq;
  3792. long ret;
  3793. current->in_iowait = 1;
  3794. blk_schedule_flush_plug(current);
  3795. delayacct_blkio_start();
  3796. rq = raw_rq();
  3797. atomic_inc(&rq->nr_iowait);
  3798. ret = schedule_timeout(timeout);
  3799. current->in_iowait = old_iowait;
  3800. atomic_dec(&rq->nr_iowait);
  3801. delayacct_blkio_end();
  3802. return ret;
  3803. }
  3804. EXPORT_SYMBOL(io_schedule_timeout);
  3805. /**
  3806. * sys_sched_get_priority_max - return maximum RT priority.
  3807. * @policy: scheduling class.
  3808. *
  3809. * Return: On success, this syscall returns the maximum
  3810. * rt_priority that can be used by a given scheduling class.
  3811. * On failure, a negative error code is returned.
  3812. */
  3813. SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
  3814. {
  3815. int ret = -EINVAL;
  3816. switch (policy) {
  3817. case SCHED_FIFO:
  3818. case SCHED_RR:
  3819. ret = MAX_USER_RT_PRIO-1;
  3820. break;
  3821. case SCHED_DEADLINE:
  3822. case SCHED_NORMAL:
  3823. case SCHED_BATCH:
  3824. case SCHED_IDLE:
  3825. ret = 0;
  3826. break;
  3827. }
  3828. return ret;
  3829. }
  3830. /**
  3831. * sys_sched_get_priority_min - return minimum RT priority.
  3832. * @policy: scheduling class.
  3833. *
  3834. * Return: On success, this syscall returns the minimum
  3835. * rt_priority that can be used by a given scheduling class.
  3836. * On failure, a negative error code is returned.
  3837. */
  3838. SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
  3839. {
  3840. int ret = -EINVAL;
  3841. switch (policy) {
  3842. case SCHED_FIFO:
  3843. case SCHED_RR:
  3844. ret = 1;
  3845. break;
  3846. case SCHED_DEADLINE:
  3847. case SCHED_NORMAL:
  3848. case SCHED_BATCH:
  3849. case SCHED_IDLE:
  3850. ret = 0;
  3851. }
  3852. return ret;
  3853. }
  3854. /**
  3855. * sys_sched_rr_get_interval - return the default timeslice of a process.
  3856. * @pid: pid of the process.
  3857. * @interval: userspace pointer to the timeslice value.
  3858. *
  3859. * this syscall writes the default timeslice value of a given process
  3860. * into the user-space timespec buffer. A value of '0' means infinity.
  3861. *
  3862. * Return: On success, 0 and the timeslice is in @interval. Otherwise,
  3863. * an error code.
  3864. */
  3865. SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
  3866. struct timespec __user *, interval)
  3867. {
  3868. struct task_struct *p;
  3869. unsigned int time_slice;
  3870. unsigned long flags;
  3871. struct rq *rq;
  3872. int retval;
  3873. struct timespec t;
  3874. if (pid < 0)
  3875. return -EINVAL;
  3876. retval = -ESRCH;
  3877. rcu_read_lock();
  3878. p = find_process_by_pid(pid);
  3879. if (!p)
  3880. goto out_unlock;
  3881. retval = security_task_getscheduler(p);
  3882. if (retval)
  3883. goto out_unlock;
  3884. rq = task_rq_lock(p, &flags);
  3885. time_slice = 0;
  3886. if (p->sched_class->get_rr_interval)
  3887. time_slice = p->sched_class->get_rr_interval(rq, p);
  3888. task_rq_unlock(rq, p, &flags);
  3889. rcu_read_unlock();
  3890. jiffies_to_timespec(time_slice, &t);
  3891. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  3892. return retval;
  3893. out_unlock:
  3894. rcu_read_unlock();
  3895. return retval;
  3896. }
  3897. static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
  3898. void sched_show_task(struct task_struct *p)
  3899. {
  3900. unsigned long free = 0;
  3901. int ppid;
  3902. unsigned long state = p->state;
  3903. if (state)
  3904. state = __ffs(state) + 1;
  3905. printk(KERN_INFO "%-15.15s %c", p->comm,
  3906. state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
  3907. #if BITS_PER_LONG == 32
  3908. if (state == TASK_RUNNING)
  3909. printk(KERN_CONT " running ");
  3910. else
  3911. printk(KERN_CONT " %08lx ", thread_saved_pc(p));
  3912. #else
  3913. if (state == TASK_RUNNING)
  3914. printk(KERN_CONT " running task ");
  3915. else
  3916. printk(KERN_CONT " %016lx ", thread_saved_pc(p));
  3917. #endif
  3918. #ifdef CONFIG_DEBUG_STACK_USAGE
  3919. free = stack_not_used(p);
  3920. #endif
  3921. ppid = 0;
  3922. rcu_read_lock();
  3923. if (pid_alive(p))
  3924. ppid = task_pid_nr(rcu_dereference(p->real_parent));
  3925. rcu_read_unlock();
  3926. printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
  3927. task_pid_nr(p), ppid,
  3928. (unsigned long)task_thread_info(p)->flags);
  3929. print_worker_info(KERN_INFO, p);
  3930. show_stack(p, NULL);
  3931. }
  3932. void show_state_filter(unsigned long state_filter)
  3933. {
  3934. struct task_struct *g, *p;
  3935. #if BITS_PER_LONG == 32
  3936. printk(KERN_INFO
  3937. " task PC stack pid father\n");
  3938. #else
  3939. printk(KERN_INFO
  3940. " task PC stack pid father\n");
  3941. #endif
  3942. rcu_read_lock();
  3943. for_each_process_thread(g, p) {
  3944. /*
  3945. * reset the NMI-timeout, listing all files on a slow
  3946. * console might take a lot of time:
  3947. */
  3948. touch_nmi_watchdog();
  3949. if (!state_filter || (p->state & state_filter))
  3950. sched_show_task(p);
  3951. }
  3952. touch_all_softlockup_watchdogs();
  3953. #ifdef CONFIG_SCHED_DEBUG
  3954. sysrq_sched_debug_show();
  3955. #endif
  3956. rcu_read_unlock();
  3957. /*
  3958. * Only show locks if all tasks are dumped:
  3959. */
  3960. if (!state_filter)
  3961. debug_show_all_locks();
  3962. }
  3963. void init_idle_bootup_task(struct task_struct *idle)
  3964. {
  3965. idle->sched_class = &idle_sched_class;
  3966. }
  3967. /**
  3968. * init_idle - set up an idle thread for a given CPU
  3969. * @idle: task in question
  3970. * @cpu: cpu the idle task belongs to
  3971. *
  3972. * NOTE: this function does not set the idle thread's NEED_RESCHED
  3973. * flag, to make booting more robust.
  3974. */
  3975. void init_idle(struct task_struct *idle, int cpu)
  3976. {
  3977. struct rq *rq = cpu_rq(cpu);
  3978. unsigned long flags;
  3979. raw_spin_lock_irqsave(&rq->lock, flags);
  3980. __sched_fork(0, idle);
  3981. idle->state = TASK_RUNNING;
  3982. idle->se.exec_start = sched_clock();
  3983. do_set_cpus_allowed(idle, cpumask_of(cpu));
  3984. /*
  3985. * We're having a chicken and egg problem, even though we are
  3986. * holding rq->lock, the cpu isn't yet set to this cpu so the
  3987. * lockdep check in task_group() will fail.
  3988. *
  3989. * Similar case to sched_fork(). / Alternatively we could
  3990. * use task_rq_lock() here and obtain the other rq->lock.
  3991. *
  3992. * Silence PROVE_RCU
  3993. */
  3994. rcu_read_lock();
  3995. __set_task_cpu(idle, cpu);
  3996. rcu_read_unlock();
  3997. rq->curr = rq->idle = idle;
  3998. idle->on_rq = TASK_ON_RQ_QUEUED;
  3999. #if defined(CONFIG_SMP)
  4000. idle->on_cpu = 1;
  4001. #endif
  4002. raw_spin_unlock_irqrestore(&rq->lock, flags);
  4003. /* Set the preempt count _outside_ the spinlocks! */
  4004. init_idle_preempt_count(idle, cpu);
  4005. /*
  4006. * The idle tasks have their own, simple scheduling class:
  4007. */
  4008. idle->sched_class = &idle_sched_class;
  4009. ftrace_graph_init_idle_task(idle, cpu);
  4010. vtime_init_idle(idle, cpu);
  4011. #if defined(CONFIG_SMP)
  4012. sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
  4013. #endif
  4014. }
  4015. int cpuset_cpumask_can_shrink(const struct cpumask *cur,
  4016. const struct cpumask *trial)
  4017. {
  4018. int ret = 1, trial_cpus;
  4019. struct dl_bw *cur_dl_b;
  4020. unsigned long flags;
  4021. if (!cpumask_weight(cur))
  4022. return ret;
  4023. rcu_read_lock_sched();
  4024. cur_dl_b = dl_bw_of(cpumask_any(cur));
  4025. trial_cpus = cpumask_weight(trial);
  4026. raw_spin_lock_irqsave(&cur_dl_b->lock, flags);
  4027. if (cur_dl_b->bw != -1 &&
  4028. cur_dl_b->bw * trial_cpus < cur_dl_b->total_bw)
  4029. ret = 0;
  4030. raw_spin_unlock_irqrestore(&cur_dl_b->lock, flags);
  4031. rcu_read_unlock_sched();
  4032. return ret;
  4033. }
  4034. int task_can_attach(struct task_struct *p,
  4035. const struct cpumask *cs_cpus_allowed)
  4036. {
  4037. int ret = 0;
  4038. /*
  4039. * Kthreads which disallow setaffinity shouldn't be moved
  4040. * to a new cpuset; we don't want to change their cpu
  4041. * affinity and isolating such threads by their set of
  4042. * allowed nodes is unnecessary. Thus, cpusets are not
  4043. * applicable for such threads. This prevents checking for
  4044. * success of set_cpus_allowed_ptr() on all attached tasks
  4045. * before cpus_allowed may be changed.
  4046. */
  4047. if (p->flags & PF_NO_SETAFFINITY) {
  4048. ret = -EINVAL;
  4049. goto out;
  4050. }
  4051. #ifdef CONFIG_SMP
  4052. if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
  4053. cs_cpus_allowed)) {
  4054. unsigned int dest_cpu = cpumask_any_and(cpu_active_mask,
  4055. cs_cpus_allowed);
  4056. struct dl_bw *dl_b;
  4057. bool overflow;
  4058. int cpus;
  4059. unsigned long flags;
  4060. rcu_read_lock_sched();
  4061. dl_b = dl_bw_of(dest_cpu);
  4062. raw_spin_lock_irqsave(&dl_b->lock, flags);
  4063. cpus = dl_bw_cpus(dest_cpu);
  4064. overflow = __dl_overflow(dl_b, cpus, 0, p->dl.dl_bw);
  4065. if (overflow)
  4066. ret = -EBUSY;
  4067. else {
  4068. /*
  4069. * We reserve space for this task in the destination
  4070. * root_domain, as we can't fail after this point.
  4071. * We will free resources in the source root_domain
  4072. * later on (see set_cpus_allowed_dl()).
  4073. */
  4074. __dl_add(dl_b, p->dl.dl_bw);
  4075. }
  4076. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  4077. rcu_read_unlock_sched();
  4078. }
  4079. #endif
  4080. out:
  4081. return ret;
  4082. }
  4083. #ifdef CONFIG_SMP
  4084. /*
  4085. * move_queued_task - move a queued task to new rq.
  4086. *
  4087. * Returns (locked) new rq. Old rq's lock is released.
  4088. */
  4089. static struct rq *move_queued_task(struct task_struct *p, int new_cpu)
  4090. {
  4091. struct rq *rq = task_rq(p);
  4092. lockdep_assert_held(&rq->lock);
  4093. dequeue_task(rq, p, 0);
  4094. p->on_rq = TASK_ON_RQ_MIGRATING;
  4095. set_task_cpu(p, new_cpu);
  4096. raw_spin_unlock(&rq->lock);
  4097. rq = cpu_rq(new_cpu);
  4098. raw_spin_lock(&rq->lock);
  4099. BUG_ON(task_cpu(p) != new_cpu);
  4100. p->on_rq = TASK_ON_RQ_QUEUED;
  4101. enqueue_task(rq, p, 0);
  4102. check_preempt_curr(rq, p, 0);
  4103. return rq;
  4104. }
  4105. void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
  4106. {
  4107. if (p->sched_class->set_cpus_allowed)
  4108. p->sched_class->set_cpus_allowed(p, new_mask);
  4109. cpumask_copy(&p->cpus_allowed, new_mask);
  4110. p->nr_cpus_allowed = cpumask_weight(new_mask);
  4111. }
  4112. /*
  4113. * This is how migration works:
  4114. *
  4115. * 1) we invoke migration_cpu_stop() on the target CPU using
  4116. * stop_one_cpu().
  4117. * 2) stopper starts to run (implicitly forcing the migrated thread
  4118. * off the CPU)
  4119. * 3) it checks whether the migrated task is still in the wrong runqueue.
  4120. * 4) if it's in the wrong runqueue then the migration thread removes
  4121. * it and puts it into the right queue.
  4122. * 5) stopper completes and stop_one_cpu() returns and the migration
  4123. * is done.
  4124. */
  4125. /*
  4126. * Change a given task's CPU affinity. Migrate the thread to a
  4127. * proper CPU and schedule it away if the CPU it's executing on
  4128. * is removed from the allowed bitmask.
  4129. *
  4130. * NOTE: the caller must have a valid reference to the task, the
  4131. * task must not exit() & deallocate itself prematurely. The
  4132. * call is not atomic; no spinlocks may be held.
  4133. */
  4134. int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
  4135. {
  4136. unsigned long flags;
  4137. struct rq *rq;
  4138. unsigned int dest_cpu;
  4139. int ret = 0;
  4140. rq = task_rq_lock(p, &flags);
  4141. if (cpumask_equal(&p->cpus_allowed, new_mask))
  4142. goto out;
  4143. if (!cpumask_intersects(new_mask, cpu_active_mask)) {
  4144. ret = -EINVAL;
  4145. goto out;
  4146. }
  4147. do_set_cpus_allowed(p, new_mask);
  4148. /* Can the task run on the task's current CPU? If so, we're done */
  4149. if (cpumask_test_cpu(task_cpu(p), new_mask))
  4150. goto out;
  4151. dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
  4152. if (task_running(rq, p) || p->state == TASK_WAKING) {
  4153. struct migration_arg arg = { p, dest_cpu };
  4154. /* Need help from migration thread: drop lock and wait. */
  4155. task_rq_unlock(rq, p, &flags);
  4156. stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
  4157. tlb_migrate_finish(p->mm);
  4158. return 0;
  4159. } else if (task_on_rq_queued(p))
  4160. rq = move_queued_task(p, dest_cpu);
  4161. out:
  4162. task_rq_unlock(rq, p, &flags);
  4163. return ret;
  4164. }
  4165. EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
  4166. /*
  4167. * Move (not current) task off this cpu, onto dest cpu. We're doing
  4168. * this because either it can't run here any more (set_cpus_allowed()
  4169. * away from this CPU, or CPU going down), or because we're
  4170. * attempting to rebalance this task on exec (sched_exec).
  4171. *
  4172. * So we race with normal scheduler movements, but that's OK, as long
  4173. * as the task is no longer on this CPU.
  4174. *
  4175. * Returns non-zero if task was successfully migrated.
  4176. */
  4177. static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
  4178. {
  4179. struct rq *rq;
  4180. int ret = 0;
  4181. if (unlikely(!cpu_active(dest_cpu)))
  4182. return ret;
  4183. rq = cpu_rq(src_cpu);
  4184. raw_spin_lock(&p->pi_lock);
  4185. raw_spin_lock(&rq->lock);
  4186. /* Already moved. */
  4187. if (task_cpu(p) != src_cpu)
  4188. goto done;
  4189. /* Affinity changed (again). */
  4190. if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p)))
  4191. goto fail;
  4192. /*
  4193. * If we're not on a rq, the next wake-up will ensure we're
  4194. * placed properly.
  4195. */
  4196. if (task_on_rq_queued(p))
  4197. rq = move_queued_task(p, dest_cpu);
  4198. done:
  4199. ret = 1;
  4200. fail:
  4201. raw_spin_unlock(&rq->lock);
  4202. raw_spin_unlock(&p->pi_lock);
  4203. return ret;
  4204. }
  4205. #ifdef CONFIG_NUMA_BALANCING
  4206. /* Migrate current task p to target_cpu */
  4207. int migrate_task_to(struct task_struct *p, int target_cpu)
  4208. {
  4209. struct migration_arg arg = { p, target_cpu };
  4210. int curr_cpu = task_cpu(p);
  4211. if (curr_cpu == target_cpu)
  4212. return 0;
  4213. if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p)))
  4214. return -EINVAL;
  4215. /* TODO: This is not properly updating schedstats */
  4216. trace_sched_move_numa(p, curr_cpu, target_cpu);
  4217. return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
  4218. }
  4219. /*
  4220. * Requeue a task on a given node and accurately track the number of NUMA
  4221. * tasks on the runqueues
  4222. */
  4223. void sched_setnuma(struct task_struct *p, int nid)
  4224. {
  4225. struct rq *rq;
  4226. unsigned long flags;
  4227. bool queued, running;
  4228. rq = task_rq_lock(p, &flags);
  4229. queued = task_on_rq_queued(p);
  4230. running = task_current(rq, p);
  4231. if (queued)
  4232. dequeue_task(rq, p, 0);
  4233. if (running)
  4234. put_prev_task(rq, p);
  4235. p->numa_preferred_nid = nid;
  4236. if (running)
  4237. p->sched_class->set_curr_task(rq);
  4238. if (queued)
  4239. enqueue_task(rq, p, 0);
  4240. task_rq_unlock(rq, p, &flags);
  4241. }
  4242. #endif
  4243. /*
  4244. * migration_cpu_stop - this will be executed by a highprio stopper thread
  4245. * and performs thread migration by bumping thread off CPU then
  4246. * 'pushing' onto another runqueue.
  4247. */
  4248. static int migration_cpu_stop(void *data)
  4249. {
  4250. struct migration_arg *arg = data;
  4251. /*
  4252. * The original target cpu might have gone down and we might
  4253. * be on another cpu but it doesn't matter.
  4254. */
  4255. local_irq_disable();
  4256. /*
  4257. * We need to explicitly wake pending tasks before running
  4258. * __migrate_task() such that we will not miss enforcing cpus_allowed
  4259. * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
  4260. */
  4261. sched_ttwu_pending();
  4262. __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
  4263. local_irq_enable();
  4264. return 0;
  4265. }
  4266. #ifdef CONFIG_HOTPLUG_CPU
  4267. /*
  4268. * Ensures that the idle task is using init_mm right before its cpu goes
  4269. * offline.
  4270. */
  4271. void idle_task_exit(void)
  4272. {
  4273. struct mm_struct *mm = current->active_mm;
  4274. BUG_ON(cpu_online(smp_processor_id()));
  4275. if (mm != &init_mm) {
  4276. switch_mm(mm, &init_mm, current);
  4277. finish_arch_post_lock_switch();
  4278. }
  4279. mmdrop(mm);
  4280. }
  4281. /*
  4282. * Since this CPU is going 'away' for a while, fold any nr_active delta
  4283. * we might have. Assumes we're called after migrate_tasks() so that the
  4284. * nr_active count is stable.
  4285. *
  4286. * Also see the comment "Global load-average calculations".
  4287. */
  4288. static void calc_load_migrate(struct rq *rq)
  4289. {
  4290. long delta = calc_load_fold_active(rq);
  4291. if (delta)
  4292. atomic_long_add(delta, &calc_load_tasks);
  4293. }
  4294. static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
  4295. {
  4296. }
  4297. static const struct sched_class fake_sched_class = {
  4298. .put_prev_task = put_prev_task_fake,
  4299. };
  4300. static struct task_struct fake_task = {
  4301. /*
  4302. * Avoid pull_{rt,dl}_task()
  4303. */
  4304. .prio = MAX_PRIO + 1,
  4305. .sched_class = &fake_sched_class,
  4306. };
  4307. /*
  4308. * Migrate all tasks from the rq, sleeping tasks will be migrated by
  4309. * try_to_wake_up()->select_task_rq().
  4310. *
  4311. * Called with rq->lock held even though we'er in stop_machine() and
  4312. * there's no concurrency possible, we hold the required locks anyway
  4313. * because of lock validation efforts.
  4314. */
  4315. static void migrate_tasks(unsigned int dead_cpu)
  4316. {
  4317. struct rq *rq = cpu_rq(dead_cpu);
  4318. struct task_struct *next, *stop = rq->stop;
  4319. int dest_cpu;
  4320. /*
  4321. * Fudge the rq selection such that the below task selection loop
  4322. * doesn't get stuck on the currently eligible stop task.
  4323. *
  4324. * We're currently inside stop_machine() and the rq is either stuck
  4325. * in the stop_machine_cpu_stop() loop, or we're executing this code,
  4326. * either way we should never end up calling schedule() until we're
  4327. * done here.
  4328. */
  4329. rq->stop = NULL;
  4330. /*
  4331. * put_prev_task() and pick_next_task() sched
  4332. * class method both need to have an up-to-date
  4333. * value of rq->clock[_task]
  4334. */
  4335. update_rq_clock(rq);
  4336. for ( ; ; ) {
  4337. /*
  4338. * There's this thread running, bail when that's the only
  4339. * remaining thread.
  4340. */
  4341. if (rq->nr_running == 1)
  4342. break;
  4343. next = pick_next_task(rq, &fake_task);
  4344. BUG_ON(!next);
  4345. next->sched_class->put_prev_task(rq, next);
  4346. /* Find suitable destination for @next, with force if needed. */
  4347. dest_cpu = select_fallback_rq(dead_cpu, next);
  4348. raw_spin_unlock(&rq->lock);
  4349. __migrate_task(next, dead_cpu, dest_cpu);
  4350. raw_spin_lock(&rq->lock);
  4351. }
  4352. rq->stop = stop;
  4353. }
  4354. #endif /* CONFIG_HOTPLUG_CPU */
  4355. #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
  4356. static struct ctl_table sd_ctl_dir[] = {
  4357. {
  4358. .procname = "sched_domain",
  4359. .mode = 0555,
  4360. },
  4361. {}
  4362. };
  4363. static struct ctl_table sd_ctl_root[] = {
  4364. {
  4365. .procname = "kernel",
  4366. .mode = 0555,
  4367. .child = sd_ctl_dir,
  4368. },
  4369. {}
  4370. };
  4371. static struct ctl_table *sd_alloc_ctl_entry(int n)
  4372. {
  4373. struct ctl_table *entry =
  4374. kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
  4375. return entry;
  4376. }
  4377. static void sd_free_ctl_entry(struct ctl_table **tablep)
  4378. {
  4379. struct ctl_table *entry;
  4380. /*
  4381. * In the intermediate directories, both the child directory and
  4382. * procname are dynamically allocated and could fail but the mode
  4383. * will always be set. In the lowest directory the names are
  4384. * static strings and all have proc handlers.
  4385. */
  4386. for (entry = *tablep; entry->mode; entry++) {
  4387. if (entry->child)
  4388. sd_free_ctl_entry(&entry->child);
  4389. if (entry->proc_handler == NULL)
  4390. kfree(entry->procname);
  4391. }
  4392. kfree(*tablep);
  4393. *tablep = NULL;
  4394. }
  4395. static int min_load_idx = 0;
  4396. static int max_load_idx = CPU_LOAD_IDX_MAX-1;
  4397. static void
  4398. set_table_entry(struct ctl_table *entry,
  4399. const char *procname, void *data, int maxlen,
  4400. umode_t mode, proc_handler *proc_handler,
  4401. bool load_idx)
  4402. {
  4403. entry->procname = procname;
  4404. entry->data = data;
  4405. entry->maxlen = maxlen;
  4406. entry->mode = mode;
  4407. entry->proc_handler = proc_handler;
  4408. if (load_idx) {
  4409. entry->extra1 = &min_load_idx;
  4410. entry->extra2 = &max_load_idx;
  4411. }
  4412. }
  4413. static struct ctl_table *
  4414. sd_alloc_ctl_domain_table(struct sched_domain *sd)
  4415. {
  4416. struct ctl_table *table = sd_alloc_ctl_entry(14);
  4417. if (table == NULL)
  4418. return NULL;
  4419. set_table_entry(&table[0], "min_interval", &sd->min_interval,
  4420. sizeof(long), 0644, proc_doulongvec_minmax, false);
  4421. set_table_entry(&table[1], "max_interval", &sd->max_interval,
  4422. sizeof(long), 0644, proc_doulongvec_minmax, false);
  4423. set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
  4424. sizeof(int), 0644, proc_dointvec_minmax, true);
  4425. set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
  4426. sizeof(int), 0644, proc_dointvec_minmax, true);
  4427. set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
  4428. sizeof(int), 0644, proc_dointvec_minmax, true);
  4429. set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
  4430. sizeof(int), 0644, proc_dointvec_minmax, true);
  4431. set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
  4432. sizeof(int), 0644, proc_dointvec_minmax, true);
  4433. set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
  4434. sizeof(int), 0644, proc_dointvec_minmax, false);
  4435. set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
  4436. sizeof(int), 0644, proc_dointvec_minmax, false);
  4437. set_table_entry(&table[9], "cache_nice_tries",
  4438. &sd->cache_nice_tries,
  4439. sizeof(int), 0644, proc_dointvec_minmax, false);
  4440. set_table_entry(&table[10], "flags", &sd->flags,
  4441. sizeof(int), 0644, proc_dointvec_minmax, false);
  4442. set_table_entry(&table[11], "max_newidle_lb_cost",
  4443. &sd->max_newidle_lb_cost,
  4444. sizeof(long), 0644, proc_doulongvec_minmax, false);
  4445. set_table_entry(&table[12], "name", sd->name,
  4446. CORENAME_MAX_SIZE, 0444, proc_dostring, false);
  4447. /* &table[13] is terminator */
  4448. return table;
  4449. }
  4450. static struct ctl_table *sd_alloc_ctl_cpu_table(int cpu)
  4451. {
  4452. struct ctl_table *entry, *table;
  4453. struct sched_domain *sd;
  4454. int domain_num = 0, i;
  4455. char buf[32];
  4456. for_each_domain(cpu, sd)
  4457. domain_num++;
  4458. entry = table = sd_alloc_ctl_entry(domain_num + 1);
  4459. if (table == NULL)
  4460. return NULL;
  4461. i = 0;
  4462. for_each_domain(cpu, sd) {
  4463. snprintf(buf, 32, "domain%d", i);
  4464. entry->procname = kstrdup(buf, GFP_KERNEL);
  4465. entry->mode = 0555;
  4466. entry->child = sd_alloc_ctl_domain_table(sd);
  4467. entry++;
  4468. i++;
  4469. }
  4470. return table;
  4471. }
  4472. static struct ctl_table_header *sd_sysctl_header;
  4473. static void register_sched_domain_sysctl(void)
  4474. {
  4475. int i, cpu_num = num_possible_cpus();
  4476. struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
  4477. char buf[32];
  4478. WARN_ON(sd_ctl_dir[0].child);
  4479. sd_ctl_dir[0].child = entry;
  4480. if (entry == NULL)
  4481. return;
  4482. for_each_possible_cpu(i) {
  4483. snprintf(buf, 32, "cpu%d", i);
  4484. entry->procname = kstrdup(buf, GFP_KERNEL);
  4485. entry->mode = 0555;
  4486. entry->child = sd_alloc_ctl_cpu_table(i);
  4487. entry++;
  4488. }
  4489. WARN_ON(sd_sysctl_header);
  4490. sd_sysctl_header = register_sysctl_table(sd_ctl_root);
  4491. }
  4492. /* may be called multiple times per register */
  4493. static void unregister_sched_domain_sysctl(void)
  4494. {
  4495. if (sd_sysctl_header)
  4496. unregister_sysctl_table(sd_sysctl_header);
  4497. sd_sysctl_header = NULL;
  4498. if (sd_ctl_dir[0].child)
  4499. sd_free_ctl_entry(&sd_ctl_dir[0].child);
  4500. }
  4501. #else
  4502. static void register_sched_domain_sysctl(void)
  4503. {
  4504. }
  4505. static void unregister_sched_domain_sysctl(void)
  4506. {
  4507. }
  4508. #endif
  4509. static void set_rq_online(struct rq *rq)
  4510. {
  4511. if (!rq->online) {
  4512. const struct sched_class *class;
  4513. cpumask_set_cpu(rq->cpu, rq->rd->online);
  4514. rq->online = 1;
  4515. for_each_class(class) {
  4516. if (class->rq_online)
  4517. class->rq_online(rq);
  4518. }
  4519. }
  4520. }
  4521. static void set_rq_offline(struct rq *rq)
  4522. {
  4523. if (rq->online) {
  4524. const struct sched_class *class;
  4525. for_each_class(class) {
  4526. if (class->rq_offline)
  4527. class->rq_offline(rq);
  4528. }
  4529. cpumask_clear_cpu(rq->cpu, rq->rd->online);
  4530. rq->online = 0;
  4531. }
  4532. }
  4533. /*
  4534. * migration_call - callback that gets triggered when a CPU is added.
  4535. * Here we can start up the necessary migration thread for the new CPU.
  4536. */
  4537. static int
  4538. migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
  4539. {
  4540. int cpu = (long)hcpu;
  4541. unsigned long flags;
  4542. struct rq *rq = cpu_rq(cpu);
  4543. switch (action & ~CPU_TASKS_FROZEN) {
  4544. case CPU_UP_PREPARE:
  4545. rq->calc_load_update = calc_load_update;
  4546. break;
  4547. case CPU_ONLINE:
  4548. /* Update our root-domain */
  4549. raw_spin_lock_irqsave(&rq->lock, flags);
  4550. if (rq->rd) {
  4551. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  4552. set_rq_online(rq);
  4553. }
  4554. raw_spin_unlock_irqrestore(&rq->lock, flags);
  4555. break;
  4556. #ifdef CONFIG_HOTPLUG_CPU
  4557. case CPU_DYING:
  4558. sched_ttwu_pending();
  4559. /* Update our root-domain */
  4560. raw_spin_lock_irqsave(&rq->lock, flags);
  4561. if (rq->rd) {
  4562. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  4563. set_rq_offline(rq);
  4564. }
  4565. migrate_tasks(cpu);
  4566. BUG_ON(rq->nr_running != 1); /* the migration thread */
  4567. raw_spin_unlock_irqrestore(&rq->lock, flags);
  4568. break;
  4569. case CPU_DEAD:
  4570. calc_load_migrate(rq);
  4571. break;
  4572. #endif
  4573. }
  4574. update_max_interval();
  4575. return NOTIFY_OK;
  4576. }
  4577. /*
  4578. * Register at high priority so that task migration (migrate_all_tasks)
  4579. * happens before everything else. This has to be lower priority than
  4580. * the notifier in the perf_event subsystem, though.
  4581. */
  4582. static struct notifier_block migration_notifier = {
  4583. .notifier_call = migration_call,
  4584. .priority = CPU_PRI_MIGRATION,
  4585. };
  4586. static void set_cpu_rq_start_time(void)
  4587. {
  4588. int cpu = smp_processor_id();
  4589. struct rq *rq = cpu_rq(cpu);
  4590. rq->age_stamp = sched_clock_cpu(cpu);
  4591. }
  4592. static int sched_cpu_active(struct notifier_block *nfb,
  4593. unsigned long action, void *hcpu)
  4594. {
  4595. switch (action & ~CPU_TASKS_FROZEN) {
  4596. case CPU_STARTING:
  4597. set_cpu_rq_start_time();
  4598. return NOTIFY_OK;
  4599. case CPU_DOWN_FAILED:
  4600. set_cpu_active((long)hcpu, true);
  4601. return NOTIFY_OK;
  4602. default:
  4603. return NOTIFY_DONE;
  4604. }
  4605. }
  4606. static int sched_cpu_inactive(struct notifier_block *nfb,
  4607. unsigned long action, void *hcpu)
  4608. {
  4609. switch (action & ~CPU_TASKS_FROZEN) {
  4610. case CPU_DOWN_PREPARE:
  4611. set_cpu_active((long)hcpu, false);
  4612. return NOTIFY_OK;
  4613. default:
  4614. return NOTIFY_DONE;
  4615. }
  4616. }
  4617. static int __init migration_init(void)
  4618. {
  4619. void *cpu = (void *)(long)smp_processor_id();
  4620. int err;
  4621. /* Initialize migration for the boot CPU */
  4622. err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
  4623. BUG_ON(err == NOTIFY_BAD);
  4624. migration_call(&migration_notifier, CPU_ONLINE, cpu);
  4625. register_cpu_notifier(&migration_notifier);
  4626. /* Register cpu active notifiers */
  4627. cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
  4628. cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
  4629. return 0;
  4630. }
  4631. early_initcall(migration_init);
  4632. #endif
  4633. #ifdef CONFIG_SMP
  4634. static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */
  4635. #ifdef CONFIG_SCHED_DEBUG
  4636. static __read_mostly int sched_debug_enabled;
  4637. static int __init sched_debug_setup(char *str)
  4638. {
  4639. sched_debug_enabled = 1;
  4640. return 0;
  4641. }
  4642. early_param("sched_debug", sched_debug_setup);
  4643. static inline bool sched_debug(void)
  4644. {
  4645. return sched_debug_enabled;
  4646. }
  4647. static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
  4648. struct cpumask *groupmask)
  4649. {
  4650. struct sched_group *group = sd->groups;
  4651. cpumask_clear(groupmask);
  4652. printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
  4653. if (!(sd->flags & SD_LOAD_BALANCE)) {
  4654. printk("does not load-balance\n");
  4655. if (sd->parent)
  4656. printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
  4657. " has parent");
  4658. return -1;
  4659. }
  4660. printk(KERN_CONT "span %*pbl level %s\n",
  4661. cpumask_pr_args(sched_domain_span(sd)), sd->name);
  4662. if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  4663. printk(KERN_ERR "ERROR: domain->span does not contain "
  4664. "CPU%d\n", cpu);
  4665. }
  4666. if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
  4667. printk(KERN_ERR "ERROR: domain->groups does not contain"
  4668. " CPU%d\n", cpu);
  4669. }
  4670. printk(KERN_DEBUG "%*s groups:", level + 1, "");
  4671. do {
  4672. if (!group) {
  4673. printk("\n");
  4674. printk(KERN_ERR "ERROR: group is NULL\n");
  4675. break;
  4676. }
  4677. if (!cpumask_weight(sched_group_cpus(group))) {
  4678. printk(KERN_CONT "\n");
  4679. printk(KERN_ERR "ERROR: empty group\n");
  4680. break;
  4681. }
  4682. if (!(sd->flags & SD_OVERLAP) &&
  4683. cpumask_intersects(groupmask, sched_group_cpus(group))) {
  4684. printk(KERN_CONT "\n");
  4685. printk(KERN_ERR "ERROR: repeated CPUs\n");
  4686. break;
  4687. }
  4688. cpumask_or(groupmask, groupmask, sched_group_cpus(group));
  4689. printk(KERN_CONT " %*pbl",
  4690. cpumask_pr_args(sched_group_cpus(group)));
  4691. if (group->sgc->capacity != SCHED_CAPACITY_SCALE) {
  4692. printk(KERN_CONT " (cpu_capacity = %d)",
  4693. group->sgc->capacity);
  4694. }
  4695. group = group->next;
  4696. } while (group != sd->groups);
  4697. printk(KERN_CONT "\n");
  4698. if (!cpumask_equal(sched_domain_span(sd), groupmask))
  4699. printk(KERN_ERR "ERROR: groups don't span domain->span\n");
  4700. if (sd->parent &&
  4701. !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
  4702. printk(KERN_ERR "ERROR: parent span is not a superset "
  4703. "of domain->span\n");
  4704. return 0;
  4705. }
  4706. static void sched_domain_debug(struct sched_domain *sd, int cpu)
  4707. {
  4708. int level = 0;
  4709. if (!sched_debug_enabled)
  4710. return;
  4711. if (!sd) {
  4712. printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
  4713. return;
  4714. }
  4715. printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
  4716. for (;;) {
  4717. if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask))
  4718. break;
  4719. level++;
  4720. sd = sd->parent;
  4721. if (!sd)
  4722. break;
  4723. }
  4724. }
  4725. #else /* !CONFIG_SCHED_DEBUG */
  4726. # define sched_domain_debug(sd, cpu) do { } while (0)
  4727. static inline bool sched_debug(void)
  4728. {
  4729. return false;
  4730. }
  4731. #endif /* CONFIG_SCHED_DEBUG */
  4732. static int sd_degenerate(struct sched_domain *sd)
  4733. {
  4734. if (cpumask_weight(sched_domain_span(sd)) == 1)
  4735. return 1;
  4736. /* Following flags need at least 2 groups */
  4737. if (sd->flags & (SD_LOAD_BALANCE |
  4738. SD_BALANCE_NEWIDLE |
  4739. SD_BALANCE_FORK |
  4740. SD_BALANCE_EXEC |
  4741. SD_SHARE_CPUCAPACITY |
  4742. SD_SHARE_PKG_RESOURCES |
  4743. SD_SHARE_POWERDOMAIN)) {
  4744. if (sd->groups != sd->groups->next)
  4745. return 0;
  4746. }
  4747. /* Following flags don't use groups */
  4748. if (sd->flags & (SD_WAKE_AFFINE))
  4749. return 0;
  4750. return 1;
  4751. }
  4752. static int
  4753. sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
  4754. {
  4755. unsigned long cflags = sd->flags, pflags = parent->flags;
  4756. if (sd_degenerate(parent))
  4757. return 1;
  4758. if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
  4759. return 0;
  4760. /* Flags needing groups don't count if only 1 group in parent */
  4761. if (parent->groups == parent->groups->next) {
  4762. pflags &= ~(SD_LOAD_BALANCE |
  4763. SD_BALANCE_NEWIDLE |
  4764. SD_BALANCE_FORK |
  4765. SD_BALANCE_EXEC |
  4766. SD_SHARE_CPUCAPACITY |
  4767. SD_SHARE_PKG_RESOURCES |
  4768. SD_PREFER_SIBLING |
  4769. SD_SHARE_POWERDOMAIN);
  4770. if (nr_node_ids == 1)
  4771. pflags &= ~SD_SERIALIZE;
  4772. }
  4773. if (~cflags & pflags)
  4774. return 0;
  4775. return 1;
  4776. }
  4777. static void free_rootdomain(struct rcu_head *rcu)
  4778. {
  4779. struct root_domain *rd = container_of(rcu, struct root_domain, rcu);
  4780. cpupri_cleanup(&rd->cpupri);
  4781. cpudl_cleanup(&rd->cpudl);
  4782. free_cpumask_var(rd->dlo_mask);
  4783. free_cpumask_var(rd->rto_mask);
  4784. free_cpumask_var(rd->online);
  4785. free_cpumask_var(rd->span);
  4786. kfree(rd);
  4787. }
  4788. static void rq_attach_root(struct rq *rq, struct root_domain *rd)
  4789. {
  4790. struct root_domain *old_rd = NULL;
  4791. unsigned long flags;
  4792. raw_spin_lock_irqsave(&rq->lock, flags);
  4793. if (rq->rd) {
  4794. old_rd = rq->rd;
  4795. if (cpumask_test_cpu(rq->cpu, old_rd->online))
  4796. set_rq_offline(rq);
  4797. cpumask_clear_cpu(rq->cpu, old_rd->span);
  4798. /*
  4799. * If we dont want to free the old_rd yet then
  4800. * set old_rd to NULL to skip the freeing later
  4801. * in this function:
  4802. */
  4803. if (!atomic_dec_and_test(&old_rd->refcount))
  4804. old_rd = NULL;
  4805. }
  4806. atomic_inc(&rd->refcount);
  4807. rq->rd = rd;
  4808. cpumask_set_cpu(rq->cpu, rd->span);
  4809. if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
  4810. set_rq_online(rq);
  4811. raw_spin_unlock_irqrestore(&rq->lock, flags);
  4812. if (old_rd)
  4813. call_rcu_sched(&old_rd->rcu, free_rootdomain);
  4814. }
  4815. static int init_rootdomain(struct root_domain *rd)
  4816. {
  4817. memset(rd, 0, sizeof(*rd));
  4818. if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
  4819. goto out;
  4820. if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
  4821. goto free_span;
  4822. if (!alloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL))
  4823. goto free_online;
  4824. if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
  4825. goto free_dlo_mask;
  4826. init_dl_bw(&rd->dl_bw);
  4827. if (cpudl_init(&rd->cpudl) != 0)
  4828. goto free_dlo_mask;
  4829. if (cpupri_init(&rd->cpupri) != 0)
  4830. goto free_rto_mask;
  4831. return 0;
  4832. free_rto_mask:
  4833. free_cpumask_var(rd->rto_mask);
  4834. free_dlo_mask:
  4835. free_cpumask_var(rd->dlo_mask);
  4836. free_online:
  4837. free_cpumask_var(rd->online);
  4838. free_span:
  4839. free_cpumask_var(rd->span);
  4840. out:
  4841. return -ENOMEM;
  4842. }
  4843. /*
  4844. * By default the system creates a single root-domain with all cpus as
  4845. * members (mimicking the global state we have today).
  4846. */
  4847. struct root_domain def_root_domain;
  4848. static void init_defrootdomain(void)
  4849. {
  4850. init_rootdomain(&def_root_domain);
  4851. atomic_set(&def_root_domain.refcount, 1);
  4852. }
  4853. static struct root_domain *alloc_rootdomain(void)
  4854. {
  4855. struct root_domain *rd;
  4856. rd = kmalloc(sizeof(*rd), GFP_KERNEL);
  4857. if (!rd)
  4858. return NULL;
  4859. if (init_rootdomain(rd) != 0) {
  4860. kfree(rd);
  4861. return NULL;
  4862. }
  4863. return rd;
  4864. }
  4865. static void free_sched_groups(struct sched_group *sg, int free_sgc)
  4866. {
  4867. struct sched_group *tmp, *first;
  4868. if (!sg)
  4869. return;
  4870. first = sg;
  4871. do {
  4872. tmp = sg->next;
  4873. if (free_sgc && atomic_dec_and_test(&sg->sgc->ref))
  4874. kfree(sg->sgc);
  4875. kfree(sg);
  4876. sg = tmp;
  4877. } while (sg != first);
  4878. }
  4879. static void free_sched_domain(struct rcu_head *rcu)
  4880. {
  4881. struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu);
  4882. /*
  4883. * If its an overlapping domain it has private groups, iterate and
  4884. * nuke them all.
  4885. */
  4886. if (sd->flags & SD_OVERLAP) {
  4887. free_sched_groups(sd->groups, 1);
  4888. } else if (atomic_dec_and_test(&sd->groups->ref)) {
  4889. kfree(sd->groups->sgc);
  4890. kfree(sd->groups);
  4891. }
  4892. kfree(sd);
  4893. }
  4894. static void destroy_sched_domain(struct sched_domain *sd, int cpu)
  4895. {
  4896. call_rcu(&sd->rcu, free_sched_domain);
  4897. }
  4898. static void destroy_sched_domains(struct sched_domain *sd, int cpu)
  4899. {
  4900. for (; sd; sd = sd->parent)
  4901. destroy_sched_domain(sd, cpu);
  4902. }
  4903. /*
  4904. * Keep a special pointer to the highest sched_domain that has
  4905. * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this
  4906. * allows us to avoid some pointer chasing select_idle_sibling().
  4907. *
  4908. * Also keep a unique ID per domain (we use the first cpu number in
  4909. * the cpumask of the domain), this allows us to quickly tell if
  4910. * two cpus are in the same cache domain, see cpus_share_cache().
  4911. */
  4912. DEFINE_PER_CPU(struct sched_domain *, sd_llc);
  4913. DEFINE_PER_CPU(int, sd_llc_size);
  4914. DEFINE_PER_CPU(int, sd_llc_id);
  4915. DEFINE_PER_CPU(struct sched_domain *, sd_numa);
  4916. DEFINE_PER_CPU(struct sched_domain *, sd_busy);
  4917. DEFINE_PER_CPU(struct sched_domain *, sd_asym);
  4918. static void update_top_cache_domain(int cpu)
  4919. {
  4920. struct sched_domain *sd;
  4921. struct sched_domain *busy_sd = NULL;
  4922. int id = cpu;
  4923. int size = 1;
  4924. sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES);
  4925. if (sd) {
  4926. id = cpumask_first(sched_domain_span(sd));
  4927. size = cpumask_weight(sched_domain_span(sd));
  4928. busy_sd = sd->parent; /* sd_busy */
  4929. }
  4930. rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd);
  4931. rcu_assign_pointer(per_cpu(sd_llc, cpu), sd);
  4932. per_cpu(sd_llc_size, cpu) = size;
  4933. per_cpu(sd_llc_id, cpu) = id;
  4934. sd = lowest_flag_domain(cpu, SD_NUMA);
  4935. rcu_assign_pointer(per_cpu(sd_numa, cpu), sd);
  4936. sd = highest_flag_domain(cpu, SD_ASYM_PACKING);
  4937. rcu_assign_pointer(per_cpu(sd_asym, cpu), sd);
  4938. }
  4939. /*
  4940. * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
  4941. * hold the hotplug lock.
  4942. */
  4943. static void
  4944. cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
  4945. {
  4946. struct rq *rq = cpu_rq(cpu);
  4947. struct sched_domain *tmp;
  4948. /* Remove the sched domains which do not contribute to scheduling. */
  4949. for (tmp = sd; tmp; ) {
  4950. struct sched_domain *parent = tmp->parent;
  4951. if (!parent)
  4952. break;
  4953. if (sd_parent_degenerate(tmp, parent)) {
  4954. tmp->parent = parent->parent;
  4955. if (parent->parent)
  4956. parent->parent->child = tmp;
  4957. /*
  4958. * Transfer SD_PREFER_SIBLING down in case of a
  4959. * degenerate parent; the spans match for this
  4960. * so the property transfers.
  4961. */
  4962. if (parent->flags & SD_PREFER_SIBLING)
  4963. tmp->flags |= SD_PREFER_SIBLING;
  4964. destroy_sched_domain(parent, cpu);
  4965. } else
  4966. tmp = tmp->parent;
  4967. }
  4968. if (sd && sd_degenerate(sd)) {
  4969. tmp = sd;
  4970. sd = sd->parent;
  4971. destroy_sched_domain(tmp, cpu);
  4972. if (sd)
  4973. sd->child = NULL;
  4974. }
  4975. sched_domain_debug(sd, cpu);
  4976. rq_attach_root(rq, rd);
  4977. tmp = rq->sd;
  4978. rcu_assign_pointer(rq->sd, sd);
  4979. destroy_sched_domains(tmp, cpu);
  4980. update_top_cache_domain(cpu);
  4981. }
  4982. /* Setup the mask of cpus configured for isolated domains */
  4983. static int __init isolated_cpu_setup(char *str)
  4984. {
  4985. alloc_bootmem_cpumask_var(&cpu_isolated_map);
  4986. cpulist_parse(str, cpu_isolated_map);
  4987. return 1;
  4988. }
  4989. __setup("isolcpus=", isolated_cpu_setup);
  4990. struct s_data {
  4991. struct sched_domain ** __percpu sd;
  4992. struct root_domain *rd;
  4993. };
  4994. enum s_alloc {
  4995. sa_rootdomain,
  4996. sa_sd,
  4997. sa_sd_storage,
  4998. sa_none,
  4999. };
  5000. /*
  5001. * Build an iteration mask that can exclude certain CPUs from the upwards
  5002. * domain traversal.
  5003. *
  5004. * Asymmetric node setups can result in situations where the domain tree is of
  5005. * unequal depth, make sure to skip domains that already cover the entire
  5006. * range.
  5007. *
  5008. * In that case build_sched_domains() will have terminated the iteration early
  5009. * and our sibling sd spans will be empty. Domains should always include the
  5010. * cpu they're built on, so check that.
  5011. *
  5012. */
  5013. static void build_group_mask(struct sched_domain *sd, struct sched_group *sg)
  5014. {
  5015. const struct cpumask *span = sched_domain_span(sd);
  5016. struct sd_data *sdd = sd->private;
  5017. struct sched_domain *sibling;
  5018. int i;
  5019. for_each_cpu(i, span) {
  5020. sibling = *per_cpu_ptr(sdd->sd, i);
  5021. if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
  5022. continue;
  5023. cpumask_set_cpu(i, sched_group_mask(sg));
  5024. }
  5025. }
  5026. /*
  5027. * Return the canonical balance cpu for this group, this is the first cpu
  5028. * of this group that's also in the iteration mask.
  5029. */
  5030. int group_balance_cpu(struct sched_group *sg)
  5031. {
  5032. return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg));
  5033. }
  5034. static int
  5035. build_overlap_sched_groups(struct sched_domain *sd, int cpu)
  5036. {
  5037. struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg;
  5038. const struct cpumask *span = sched_domain_span(sd);
  5039. struct cpumask *covered = sched_domains_tmpmask;
  5040. struct sd_data *sdd = sd->private;
  5041. struct sched_domain *sibling;
  5042. int i;
  5043. cpumask_clear(covered);
  5044. for_each_cpu(i, span) {
  5045. struct cpumask *sg_span;
  5046. if (cpumask_test_cpu(i, covered))
  5047. continue;
  5048. sibling = *per_cpu_ptr(sdd->sd, i);
  5049. /* See the comment near build_group_mask(). */
  5050. if (!cpumask_test_cpu(i, sched_domain_span(sibling)))
  5051. continue;
  5052. sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
  5053. GFP_KERNEL, cpu_to_node(cpu));
  5054. if (!sg)
  5055. goto fail;
  5056. sg_span = sched_group_cpus(sg);
  5057. if (sibling->child)
  5058. cpumask_copy(sg_span, sched_domain_span(sibling->child));
  5059. else
  5060. cpumask_set_cpu(i, sg_span);
  5061. cpumask_or(covered, covered, sg_span);
  5062. sg->sgc = *per_cpu_ptr(sdd->sgc, i);
  5063. if (atomic_inc_return(&sg->sgc->ref) == 1)
  5064. build_group_mask(sd, sg);
  5065. /*
  5066. * Initialize sgc->capacity such that even if we mess up the
  5067. * domains and no possible iteration will get us here, we won't
  5068. * die on a /0 trap.
  5069. */
  5070. sg->sgc->capacity = SCHED_CAPACITY_SCALE * cpumask_weight(sg_span);
  5071. /*
  5072. * Make sure the first group of this domain contains the
  5073. * canonical balance cpu. Otherwise the sched_domain iteration
  5074. * breaks. See update_sg_lb_stats().
  5075. */
  5076. if ((!groups && cpumask_test_cpu(cpu, sg_span)) ||
  5077. group_balance_cpu(sg) == cpu)
  5078. groups = sg;
  5079. if (!first)
  5080. first = sg;
  5081. if (last)
  5082. last->next = sg;
  5083. last = sg;
  5084. last->next = first;
  5085. }
  5086. sd->groups = groups;
  5087. return 0;
  5088. fail:
  5089. free_sched_groups(first, 0);
  5090. return -ENOMEM;
  5091. }
  5092. static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg)
  5093. {
  5094. struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu);
  5095. struct sched_domain *child = sd->child;
  5096. if (child)
  5097. cpu = cpumask_first(sched_domain_span(child));
  5098. if (sg) {
  5099. *sg = *per_cpu_ptr(sdd->sg, cpu);
  5100. (*sg)->sgc = *per_cpu_ptr(sdd->sgc, cpu);
  5101. atomic_set(&(*sg)->sgc->ref, 1); /* for claim_allocations */
  5102. }
  5103. return cpu;
  5104. }
  5105. /*
  5106. * build_sched_groups will build a circular linked list of the groups
  5107. * covered by the given span, and will set each group's ->cpumask correctly,
  5108. * and ->cpu_capacity to 0.
  5109. *
  5110. * Assumes the sched_domain tree is fully constructed
  5111. */
  5112. static int
  5113. build_sched_groups(struct sched_domain *sd, int cpu)
  5114. {
  5115. struct sched_group *first = NULL, *last = NULL;
  5116. struct sd_data *sdd = sd->private;
  5117. const struct cpumask *span = sched_domain_span(sd);
  5118. struct cpumask *covered;
  5119. int i;
  5120. get_group(cpu, sdd, &sd->groups);
  5121. atomic_inc(&sd->groups->ref);
  5122. if (cpu != cpumask_first(span))
  5123. return 0;
  5124. lockdep_assert_held(&sched_domains_mutex);
  5125. covered = sched_domains_tmpmask;
  5126. cpumask_clear(covered);
  5127. for_each_cpu(i, span) {
  5128. struct sched_group *sg;
  5129. int group, j;
  5130. if (cpumask_test_cpu(i, covered))
  5131. continue;
  5132. group = get_group(i, sdd, &sg);
  5133. cpumask_setall(sched_group_mask(sg));
  5134. for_each_cpu(j, span) {
  5135. if (get_group(j, sdd, NULL) != group)
  5136. continue;
  5137. cpumask_set_cpu(j, covered);
  5138. cpumask_set_cpu(j, sched_group_cpus(sg));
  5139. }
  5140. if (!first)
  5141. first = sg;
  5142. if (last)
  5143. last->next = sg;
  5144. last = sg;
  5145. }
  5146. last->next = first;
  5147. return 0;
  5148. }
  5149. /*
  5150. * Initialize sched groups cpu_capacity.
  5151. *
  5152. * cpu_capacity indicates the capacity of sched group, which is used while
  5153. * distributing the load between different sched groups in a sched domain.
  5154. * Typically cpu_capacity for all the groups in a sched domain will be same
  5155. * unless there are asymmetries in the topology. If there are asymmetries,
  5156. * group having more cpu_capacity will pickup more load compared to the
  5157. * group having less cpu_capacity.
  5158. */
  5159. static void init_sched_groups_capacity(int cpu, struct sched_domain *sd)
  5160. {
  5161. struct sched_group *sg = sd->groups;
  5162. WARN_ON(!sg);
  5163. do {
  5164. sg->group_weight = cpumask_weight(sched_group_cpus(sg));
  5165. sg = sg->next;
  5166. } while (sg != sd->groups);
  5167. if (cpu != group_balance_cpu(sg))
  5168. return;
  5169. update_group_capacity(sd, cpu);
  5170. atomic_set(&sg->sgc->nr_busy_cpus, sg->group_weight);
  5171. }
  5172. /*
  5173. * Initializers for schedule domains
  5174. * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
  5175. */
  5176. static int default_relax_domain_level = -1;
  5177. int sched_domain_level_max;
  5178. static int __init setup_relax_domain_level(char *str)
  5179. {
  5180. if (kstrtoint(str, 0, &default_relax_domain_level))
  5181. pr_warn("Unable to set relax_domain_level\n");
  5182. return 1;
  5183. }
  5184. __setup("relax_domain_level=", setup_relax_domain_level);
  5185. static void set_domain_attribute(struct sched_domain *sd,
  5186. struct sched_domain_attr *attr)
  5187. {
  5188. int request;
  5189. if (!attr || attr->relax_domain_level < 0) {
  5190. if (default_relax_domain_level < 0)
  5191. return;
  5192. else
  5193. request = default_relax_domain_level;
  5194. } else
  5195. request = attr->relax_domain_level;
  5196. if (request < sd->level) {
  5197. /* turn off idle balance on this domain */
  5198. sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
  5199. } else {
  5200. /* turn on idle balance on this domain */
  5201. sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
  5202. }
  5203. }
  5204. static void __sdt_free(const struct cpumask *cpu_map);
  5205. static int __sdt_alloc(const struct cpumask *cpu_map);
  5206. static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
  5207. const struct cpumask *cpu_map)
  5208. {
  5209. switch (what) {
  5210. case sa_rootdomain:
  5211. if (!atomic_read(&d->rd->refcount))
  5212. free_rootdomain(&d->rd->rcu); /* fall through */
  5213. case sa_sd:
  5214. free_percpu(d->sd); /* fall through */
  5215. case sa_sd_storage:
  5216. __sdt_free(cpu_map); /* fall through */
  5217. case sa_none:
  5218. break;
  5219. }
  5220. }
  5221. static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
  5222. const struct cpumask *cpu_map)
  5223. {
  5224. memset(d, 0, sizeof(*d));
  5225. if (__sdt_alloc(cpu_map))
  5226. return sa_sd_storage;
  5227. d->sd = alloc_percpu(struct sched_domain *);
  5228. if (!d->sd)
  5229. return sa_sd_storage;
  5230. d->rd = alloc_rootdomain();
  5231. if (!d->rd)
  5232. return sa_sd;
  5233. return sa_rootdomain;
  5234. }
  5235. /*
  5236. * NULL the sd_data elements we've used to build the sched_domain and
  5237. * sched_group structure so that the subsequent __free_domain_allocs()
  5238. * will not free the data we're using.
  5239. */
  5240. static void claim_allocations(int cpu, struct sched_domain *sd)
  5241. {
  5242. struct sd_data *sdd = sd->private;
  5243. WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd);
  5244. *per_cpu_ptr(sdd->sd, cpu) = NULL;
  5245. if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref))
  5246. *per_cpu_ptr(sdd->sg, cpu) = NULL;
  5247. if (atomic_read(&(*per_cpu_ptr(sdd->sgc, cpu))->ref))
  5248. *per_cpu_ptr(sdd->sgc, cpu) = NULL;
  5249. }
  5250. #ifdef CONFIG_NUMA
  5251. static int sched_domains_numa_levels;
  5252. enum numa_topology_type sched_numa_topology_type;
  5253. static int *sched_domains_numa_distance;
  5254. int sched_max_numa_distance;
  5255. static struct cpumask ***sched_domains_numa_masks;
  5256. static int sched_domains_curr_level;
  5257. #endif
  5258. /*
  5259. * SD_flags allowed in topology descriptions.
  5260. *
  5261. * SD_SHARE_CPUCAPACITY - describes SMT topologies
  5262. * SD_SHARE_PKG_RESOURCES - describes shared caches
  5263. * SD_NUMA - describes NUMA topologies
  5264. * SD_SHARE_POWERDOMAIN - describes shared power domain
  5265. *
  5266. * Odd one out:
  5267. * SD_ASYM_PACKING - describes SMT quirks
  5268. */
  5269. #define TOPOLOGY_SD_FLAGS \
  5270. (SD_SHARE_CPUCAPACITY | \
  5271. SD_SHARE_PKG_RESOURCES | \
  5272. SD_NUMA | \
  5273. SD_ASYM_PACKING | \
  5274. SD_SHARE_POWERDOMAIN)
  5275. static struct sched_domain *
  5276. sd_init(struct sched_domain_topology_level *tl, int cpu)
  5277. {
  5278. struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu);
  5279. int sd_weight, sd_flags = 0;
  5280. #ifdef CONFIG_NUMA
  5281. /*
  5282. * Ugly hack to pass state to sd_numa_mask()...
  5283. */
  5284. sched_domains_curr_level = tl->numa_level;
  5285. #endif
  5286. sd_weight = cpumask_weight(tl->mask(cpu));
  5287. if (tl->sd_flags)
  5288. sd_flags = (*tl->sd_flags)();
  5289. if (WARN_ONCE(sd_flags & ~TOPOLOGY_SD_FLAGS,
  5290. "wrong sd_flags in topology description\n"))
  5291. sd_flags &= ~TOPOLOGY_SD_FLAGS;
  5292. *sd = (struct sched_domain){
  5293. .min_interval = sd_weight,
  5294. .max_interval = 2*sd_weight,
  5295. .busy_factor = 32,
  5296. .imbalance_pct = 125,
  5297. .cache_nice_tries = 0,
  5298. .busy_idx = 0,
  5299. .idle_idx = 0,
  5300. .newidle_idx = 0,
  5301. .wake_idx = 0,
  5302. .forkexec_idx = 0,
  5303. .flags = 1*SD_LOAD_BALANCE
  5304. | 1*SD_BALANCE_NEWIDLE
  5305. | 1*SD_BALANCE_EXEC
  5306. | 1*SD_BALANCE_FORK
  5307. | 0*SD_BALANCE_WAKE
  5308. | 1*SD_WAKE_AFFINE
  5309. | 0*SD_SHARE_CPUCAPACITY
  5310. | 0*SD_SHARE_PKG_RESOURCES
  5311. | 0*SD_SERIALIZE
  5312. | 0*SD_PREFER_SIBLING
  5313. | 0*SD_NUMA
  5314. | sd_flags
  5315. ,
  5316. .last_balance = jiffies,
  5317. .balance_interval = sd_weight,
  5318. .smt_gain = 0,
  5319. .max_newidle_lb_cost = 0,
  5320. .next_decay_max_lb_cost = jiffies,
  5321. #ifdef CONFIG_SCHED_DEBUG
  5322. .name = tl->name,
  5323. #endif
  5324. };
  5325. /*
  5326. * Convert topological properties into behaviour.
  5327. */
  5328. if (sd->flags & SD_SHARE_CPUCAPACITY) {
  5329. sd->flags |= SD_PREFER_SIBLING;
  5330. sd->imbalance_pct = 110;
  5331. sd->smt_gain = 1178; /* ~15% */
  5332. } else if (sd->flags & SD_SHARE_PKG_RESOURCES) {
  5333. sd->imbalance_pct = 117;
  5334. sd->cache_nice_tries = 1;
  5335. sd->busy_idx = 2;
  5336. #ifdef CONFIG_NUMA
  5337. } else if (sd->flags & SD_NUMA) {
  5338. sd->cache_nice_tries = 2;
  5339. sd->busy_idx = 3;
  5340. sd->idle_idx = 2;
  5341. sd->flags |= SD_SERIALIZE;
  5342. if (sched_domains_numa_distance[tl->numa_level] > RECLAIM_DISTANCE) {
  5343. sd->flags &= ~(SD_BALANCE_EXEC |
  5344. SD_BALANCE_FORK |
  5345. SD_WAKE_AFFINE);
  5346. }
  5347. #endif
  5348. } else {
  5349. sd->flags |= SD_PREFER_SIBLING;
  5350. sd->cache_nice_tries = 1;
  5351. sd->busy_idx = 2;
  5352. sd->idle_idx = 1;
  5353. }
  5354. sd->private = &tl->data;
  5355. return sd;
  5356. }
  5357. /*
  5358. * Topology list, bottom-up.
  5359. */
  5360. static struct sched_domain_topology_level default_topology[] = {
  5361. #ifdef CONFIG_SCHED_SMT
  5362. { cpu_smt_mask, cpu_smt_flags, SD_INIT_NAME(SMT) },
  5363. #endif
  5364. #ifdef CONFIG_SCHED_MC
  5365. { cpu_coregroup_mask, cpu_core_flags, SD_INIT_NAME(MC) },
  5366. #endif
  5367. { cpu_cpu_mask, SD_INIT_NAME(DIE) },
  5368. { NULL, },
  5369. };
  5370. struct sched_domain_topology_level *sched_domain_topology = default_topology;
  5371. #define for_each_sd_topology(tl) \
  5372. for (tl = sched_domain_topology; tl->mask; tl++)
  5373. void set_sched_topology(struct sched_domain_topology_level *tl)
  5374. {
  5375. sched_domain_topology = tl;
  5376. }
  5377. #ifdef CONFIG_NUMA
  5378. static const struct cpumask *sd_numa_mask(int cpu)
  5379. {
  5380. return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)];
  5381. }
  5382. static void sched_numa_warn(const char *str)
  5383. {
  5384. static int done = false;
  5385. int i,j;
  5386. if (done)
  5387. return;
  5388. done = true;
  5389. printk(KERN_WARNING "ERROR: %s\n\n", str);
  5390. for (i = 0; i < nr_node_ids; i++) {
  5391. printk(KERN_WARNING " ");
  5392. for (j = 0; j < nr_node_ids; j++)
  5393. printk(KERN_CONT "%02d ", node_distance(i,j));
  5394. printk(KERN_CONT "\n");
  5395. }
  5396. printk(KERN_WARNING "\n");
  5397. }
  5398. bool find_numa_distance(int distance)
  5399. {
  5400. int i;
  5401. if (distance == node_distance(0, 0))
  5402. return true;
  5403. for (i = 0; i < sched_domains_numa_levels; i++) {
  5404. if (sched_domains_numa_distance[i] == distance)
  5405. return true;
  5406. }
  5407. return false;
  5408. }
  5409. /*
  5410. * A system can have three types of NUMA topology:
  5411. * NUMA_DIRECT: all nodes are directly connected, or not a NUMA system
  5412. * NUMA_GLUELESS_MESH: some nodes reachable through intermediary nodes
  5413. * NUMA_BACKPLANE: nodes can reach other nodes through a backplane
  5414. *
  5415. * The difference between a glueless mesh topology and a backplane
  5416. * topology lies in whether communication between not directly
  5417. * connected nodes goes through intermediary nodes (where programs
  5418. * could run), or through backplane controllers. This affects
  5419. * placement of programs.
  5420. *
  5421. * The type of topology can be discerned with the following tests:
  5422. * - If the maximum distance between any nodes is 1 hop, the system
  5423. * is directly connected.
  5424. * - If for two nodes A and B, located N > 1 hops away from each other,
  5425. * there is an intermediary node C, which is < N hops away from both
  5426. * nodes A and B, the system is a glueless mesh.
  5427. */
  5428. static void init_numa_topology_type(void)
  5429. {
  5430. int a, b, c, n;
  5431. n = sched_max_numa_distance;
  5432. if (n <= 1)
  5433. sched_numa_topology_type = NUMA_DIRECT;
  5434. for_each_online_node(a) {
  5435. for_each_online_node(b) {
  5436. /* Find two nodes furthest removed from each other. */
  5437. if (node_distance(a, b) < n)
  5438. continue;
  5439. /* Is there an intermediary node between a and b? */
  5440. for_each_online_node(c) {
  5441. if (node_distance(a, c) < n &&
  5442. node_distance(b, c) < n) {
  5443. sched_numa_topology_type =
  5444. NUMA_GLUELESS_MESH;
  5445. return;
  5446. }
  5447. }
  5448. sched_numa_topology_type = NUMA_BACKPLANE;
  5449. return;
  5450. }
  5451. }
  5452. }
  5453. static void sched_init_numa(void)
  5454. {
  5455. int next_distance, curr_distance = node_distance(0, 0);
  5456. struct sched_domain_topology_level *tl;
  5457. int level = 0;
  5458. int i, j, k;
  5459. sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL);
  5460. if (!sched_domains_numa_distance)
  5461. return;
  5462. /*
  5463. * O(nr_nodes^2) deduplicating selection sort -- in order to find the
  5464. * unique distances in the node_distance() table.
  5465. *
  5466. * Assumes node_distance(0,j) includes all distances in
  5467. * node_distance(i,j) in order to avoid cubic time.
  5468. */
  5469. next_distance = curr_distance;
  5470. for (i = 0; i < nr_node_ids; i++) {
  5471. for (j = 0; j < nr_node_ids; j++) {
  5472. for (k = 0; k < nr_node_ids; k++) {
  5473. int distance = node_distance(i, k);
  5474. if (distance > curr_distance &&
  5475. (distance < next_distance ||
  5476. next_distance == curr_distance))
  5477. next_distance = distance;
  5478. /*
  5479. * While not a strong assumption it would be nice to know
  5480. * about cases where if node A is connected to B, B is not
  5481. * equally connected to A.
  5482. */
  5483. if (sched_debug() && node_distance(k, i) != distance)
  5484. sched_numa_warn("Node-distance not symmetric");
  5485. if (sched_debug() && i && !find_numa_distance(distance))
  5486. sched_numa_warn("Node-0 not representative");
  5487. }
  5488. if (next_distance != curr_distance) {
  5489. sched_domains_numa_distance[level++] = next_distance;
  5490. sched_domains_numa_levels = level;
  5491. curr_distance = next_distance;
  5492. } else break;
  5493. }
  5494. /*
  5495. * In case of sched_debug() we verify the above assumption.
  5496. */
  5497. if (!sched_debug())
  5498. break;
  5499. }
  5500. if (!level)
  5501. return;
  5502. /*
  5503. * 'level' contains the number of unique distances, excluding the
  5504. * identity distance node_distance(i,i).
  5505. *
  5506. * The sched_domains_numa_distance[] array includes the actual distance
  5507. * numbers.
  5508. */
  5509. /*
  5510. * Here, we should temporarily reset sched_domains_numa_levels to 0.
  5511. * If it fails to allocate memory for array sched_domains_numa_masks[][],
  5512. * the array will contain less then 'level' members. This could be
  5513. * dangerous when we use it to iterate array sched_domains_numa_masks[][]
  5514. * in other functions.
  5515. *
  5516. * We reset it to 'level' at the end of this function.
  5517. */
  5518. sched_domains_numa_levels = 0;
  5519. sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL);
  5520. if (!sched_domains_numa_masks)
  5521. return;
  5522. /*
  5523. * Now for each level, construct a mask per node which contains all
  5524. * cpus of nodes that are that many hops away from us.
  5525. */
  5526. for (i = 0; i < level; i++) {
  5527. sched_domains_numa_masks[i] =
  5528. kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL);
  5529. if (!sched_domains_numa_masks[i])
  5530. return;
  5531. for (j = 0; j < nr_node_ids; j++) {
  5532. struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL);
  5533. if (!mask)
  5534. return;
  5535. sched_domains_numa_masks[i][j] = mask;
  5536. for (k = 0; k < nr_node_ids; k++) {
  5537. if (node_distance(j, k) > sched_domains_numa_distance[i])
  5538. continue;
  5539. cpumask_or(mask, mask, cpumask_of_node(k));
  5540. }
  5541. }
  5542. }
  5543. /* Compute default topology size */
  5544. for (i = 0; sched_domain_topology[i].mask; i++);
  5545. tl = kzalloc((i + level + 1) *
  5546. sizeof(struct sched_domain_topology_level), GFP_KERNEL);
  5547. if (!tl)
  5548. return;
  5549. /*
  5550. * Copy the default topology bits..
  5551. */
  5552. for (i = 0; sched_domain_topology[i].mask; i++)
  5553. tl[i] = sched_domain_topology[i];
  5554. /*
  5555. * .. and append 'j' levels of NUMA goodness.
  5556. */
  5557. for (j = 0; j < level; i++, j++) {
  5558. tl[i] = (struct sched_domain_topology_level){
  5559. .mask = sd_numa_mask,
  5560. .sd_flags = cpu_numa_flags,
  5561. .flags = SDTL_OVERLAP,
  5562. .numa_level = j,
  5563. SD_INIT_NAME(NUMA)
  5564. };
  5565. }
  5566. sched_domain_topology = tl;
  5567. sched_domains_numa_levels = level;
  5568. sched_max_numa_distance = sched_domains_numa_distance[level - 1];
  5569. init_numa_topology_type();
  5570. }
  5571. static void sched_domains_numa_masks_set(int cpu)
  5572. {
  5573. int i, j;
  5574. int node = cpu_to_node(cpu);
  5575. for (i = 0; i < sched_domains_numa_levels; i++) {
  5576. for (j = 0; j < nr_node_ids; j++) {
  5577. if (node_distance(j, node) <= sched_domains_numa_distance[i])
  5578. cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]);
  5579. }
  5580. }
  5581. }
  5582. static void sched_domains_numa_masks_clear(int cpu)
  5583. {
  5584. int i, j;
  5585. for (i = 0; i < sched_domains_numa_levels; i++) {
  5586. for (j = 0; j < nr_node_ids; j++)
  5587. cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]);
  5588. }
  5589. }
  5590. /*
  5591. * Update sched_domains_numa_masks[level][node] array when new cpus
  5592. * are onlined.
  5593. */
  5594. static int sched_domains_numa_masks_update(struct notifier_block *nfb,
  5595. unsigned long action,
  5596. void *hcpu)
  5597. {
  5598. int cpu = (long)hcpu;
  5599. switch (action & ~CPU_TASKS_FROZEN) {
  5600. case CPU_ONLINE:
  5601. sched_domains_numa_masks_set(cpu);
  5602. break;
  5603. case CPU_DEAD:
  5604. sched_domains_numa_masks_clear(cpu);
  5605. break;
  5606. default:
  5607. return NOTIFY_DONE;
  5608. }
  5609. return NOTIFY_OK;
  5610. }
  5611. #else
  5612. static inline void sched_init_numa(void)
  5613. {
  5614. }
  5615. static int sched_domains_numa_masks_update(struct notifier_block *nfb,
  5616. unsigned long action,
  5617. void *hcpu)
  5618. {
  5619. return 0;
  5620. }
  5621. #endif /* CONFIG_NUMA */
  5622. static int __sdt_alloc(const struct cpumask *cpu_map)
  5623. {
  5624. struct sched_domain_topology_level *tl;
  5625. int j;
  5626. for_each_sd_topology(tl) {
  5627. struct sd_data *sdd = &tl->data;
  5628. sdd->sd = alloc_percpu(struct sched_domain *);
  5629. if (!sdd->sd)
  5630. return -ENOMEM;
  5631. sdd->sg = alloc_percpu(struct sched_group *);
  5632. if (!sdd->sg)
  5633. return -ENOMEM;
  5634. sdd->sgc = alloc_percpu(struct sched_group_capacity *);
  5635. if (!sdd->sgc)
  5636. return -ENOMEM;
  5637. for_each_cpu(j, cpu_map) {
  5638. struct sched_domain *sd;
  5639. struct sched_group *sg;
  5640. struct sched_group_capacity *sgc;
  5641. sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(),
  5642. GFP_KERNEL, cpu_to_node(j));
  5643. if (!sd)
  5644. return -ENOMEM;
  5645. *per_cpu_ptr(sdd->sd, j) = sd;
  5646. sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(),
  5647. GFP_KERNEL, cpu_to_node(j));
  5648. if (!sg)
  5649. return -ENOMEM;
  5650. sg->next = sg;
  5651. *per_cpu_ptr(sdd->sg, j) = sg;
  5652. sgc = kzalloc_node(sizeof(struct sched_group_capacity) + cpumask_size(),
  5653. GFP_KERNEL, cpu_to_node(j));
  5654. if (!sgc)
  5655. return -ENOMEM;
  5656. *per_cpu_ptr(sdd->sgc, j) = sgc;
  5657. }
  5658. }
  5659. return 0;
  5660. }
  5661. static void __sdt_free(const struct cpumask *cpu_map)
  5662. {
  5663. struct sched_domain_topology_level *tl;
  5664. int j;
  5665. for_each_sd_topology(tl) {
  5666. struct sd_data *sdd = &tl->data;
  5667. for_each_cpu(j, cpu_map) {
  5668. struct sched_domain *sd;
  5669. if (sdd->sd) {
  5670. sd = *per_cpu_ptr(sdd->sd, j);
  5671. if (sd && (sd->flags & SD_OVERLAP))
  5672. free_sched_groups(sd->groups, 0);
  5673. kfree(*per_cpu_ptr(sdd->sd, j));
  5674. }
  5675. if (sdd->sg)
  5676. kfree(*per_cpu_ptr(sdd->sg, j));
  5677. if (sdd->sgc)
  5678. kfree(*per_cpu_ptr(sdd->sgc, j));
  5679. }
  5680. free_percpu(sdd->sd);
  5681. sdd->sd = NULL;
  5682. free_percpu(sdd->sg);
  5683. sdd->sg = NULL;
  5684. free_percpu(sdd->sgc);
  5685. sdd->sgc = NULL;
  5686. }
  5687. }
  5688. struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl,
  5689. const struct cpumask *cpu_map, struct sched_domain_attr *attr,
  5690. struct sched_domain *child, int cpu)
  5691. {
  5692. struct sched_domain *sd = sd_init(tl, cpu);
  5693. if (!sd)
  5694. return child;
  5695. cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu));
  5696. if (child) {
  5697. sd->level = child->level + 1;
  5698. sched_domain_level_max = max(sched_domain_level_max, sd->level);
  5699. child->parent = sd;
  5700. sd->child = child;
  5701. if (!cpumask_subset(sched_domain_span(child),
  5702. sched_domain_span(sd))) {
  5703. pr_err("BUG: arch topology borken\n");
  5704. #ifdef CONFIG_SCHED_DEBUG
  5705. pr_err(" the %s domain not a subset of the %s domain\n",
  5706. child->name, sd->name);
  5707. #endif
  5708. /* Fixup, ensure @sd has at least @child cpus. */
  5709. cpumask_or(sched_domain_span(sd),
  5710. sched_domain_span(sd),
  5711. sched_domain_span(child));
  5712. }
  5713. }
  5714. set_domain_attribute(sd, attr);
  5715. return sd;
  5716. }
  5717. /*
  5718. * Build sched domains for a given set of cpus and attach the sched domains
  5719. * to the individual cpus
  5720. */
  5721. static int build_sched_domains(const struct cpumask *cpu_map,
  5722. struct sched_domain_attr *attr)
  5723. {
  5724. enum s_alloc alloc_state;
  5725. struct sched_domain *sd;
  5726. struct s_data d;
  5727. int i, ret = -ENOMEM;
  5728. alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
  5729. if (alloc_state != sa_rootdomain)
  5730. goto error;
  5731. /* Set up domains for cpus specified by the cpu_map. */
  5732. for_each_cpu(i, cpu_map) {
  5733. struct sched_domain_topology_level *tl;
  5734. sd = NULL;
  5735. for_each_sd_topology(tl) {
  5736. sd = build_sched_domain(tl, cpu_map, attr, sd, i);
  5737. if (tl == sched_domain_topology)
  5738. *per_cpu_ptr(d.sd, i) = sd;
  5739. if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP))
  5740. sd->flags |= SD_OVERLAP;
  5741. if (cpumask_equal(cpu_map, sched_domain_span(sd)))
  5742. break;
  5743. }
  5744. }
  5745. /* Build the groups for the domains */
  5746. for_each_cpu(i, cpu_map) {
  5747. for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
  5748. sd->span_weight = cpumask_weight(sched_domain_span(sd));
  5749. if (sd->flags & SD_OVERLAP) {
  5750. if (build_overlap_sched_groups(sd, i))
  5751. goto error;
  5752. } else {
  5753. if (build_sched_groups(sd, i))
  5754. goto error;
  5755. }
  5756. }
  5757. }
  5758. /* Calculate CPU capacity for physical packages and nodes */
  5759. for (i = nr_cpumask_bits-1; i >= 0; i--) {
  5760. if (!cpumask_test_cpu(i, cpu_map))
  5761. continue;
  5762. for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) {
  5763. claim_allocations(i, sd);
  5764. init_sched_groups_capacity(i, sd);
  5765. }
  5766. }
  5767. /* Attach the domains */
  5768. rcu_read_lock();
  5769. for_each_cpu(i, cpu_map) {
  5770. sd = *per_cpu_ptr(d.sd, i);
  5771. cpu_attach_domain(sd, d.rd, i);
  5772. }
  5773. rcu_read_unlock();
  5774. ret = 0;
  5775. error:
  5776. __free_domain_allocs(&d, alloc_state, cpu_map);
  5777. return ret;
  5778. }
  5779. static cpumask_var_t *doms_cur; /* current sched domains */
  5780. static int ndoms_cur; /* number of sched domains in 'doms_cur' */
  5781. static struct sched_domain_attr *dattr_cur;
  5782. /* attribues of custom domains in 'doms_cur' */
  5783. /*
  5784. * Special case: If a kmalloc of a doms_cur partition (array of
  5785. * cpumask) fails, then fallback to a single sched domain,
  5786. * as determined by the single cpumask fallback_doms.
  5787. */
  5788. static cpumask_var_t fallback_doms;
  5789. /*
  5790. * arch_update_cpu_topology lets virtualized architectures update the
  5791. * cpu core maps. It is supposed to return 1 if the topology changed
  5792. * or 0 if it stayed the same.
  5793. */
  5794. int __weak arch_update_cpu_topology(void)
  5795. {
  5796. return 0;
  5797. }
  5798. cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
  5799. {
  5800. int i;
  5801. cpumask_var_t *doms;
  5802. doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
  5803. if (!doms)
  5804. return NULL;
  5805. for (i = 0; i < ndoms; i++) {
  5806. if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
  5807. free_sched_domains(doms, i);
  5808. return NULL;
  5809. }
  5810. }
  5811. return doms;
  5812. }
  5813. void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
  5814. {
  5815. unsigned int i;
  5816. for (i = 0; i < ndoms; i++)
  5817. free_cpumask_var(doms[i]);
  5818. kfree(doms);
  5819. }
  5820. /*
  5821. * Set up scheduler domains and groups. Callers must hold the hotplug lock.
  5822. * For now this just excludes isolated cpus, but could be used to
  5823. * exclude other special cases in the future.
  5824. */
  5825. static int init_sched_domains(const struct cpumask *cpu_map)
  5826. {
  5827. int err;
  5828. arch_update_cpu_topology();
  5829. ndoms_cur = 1;
  5830. doms_cur = alloc_sched_domains(ndoms_cur);
  5831. if (!doms_cur)
  5832. doms_cur = &fallback_doms;
  5833. cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
  5834. err = build_sched_domains(doms_cur[0], NULL);
  5835. register_sched_domain_sysctl();
  5836. return err;
  5837. }
  5838. /*
  5839. * Detach sched domains from a group of cpus specified in cpu_map
  5840. * These cpus will now be attached to the NULL domain
  5841. */
  5842. static void detach_destroy_domains(const struct cpumask *cpu_map)
  5843. {
  5844. int i;
  5845. rcu_read_lock();
  5846. for_each_cpu(i, cpu_map)
  5847. cpu_attach_domain(NULL, &def_root_domain, i);
  5848. rcu_read_unlock();
  5849. }
  5850. /* handle null as "default" */
  5851. static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
  5852. struct sched_domain_attr *new, int idx_new)
  5853. {
  5854. struct sched_domain_attr tmp;
  5855. /* fast path */
  5856. if (!new && !cur)
  5857. return 1;
  5858. tmp = SD_ATTR_INIT;
  5859. return !memcmp(cur ? (cur + idx_cur) : &tmp,
  5860. new ? (new + idx_new) : &tmp,
  5861. sizeof(struct sched_domain_attr));
  5862. }
  5863. /*
  5864. * Partition sched domains as specified by the 'ndoms_new'
  5865. * cpumasks in the array doms_new[] of cpumasks. This compares
  5866. * doms_new[] to the current sched domain partitioning, doms_cur[].
  5867. * It destroys each deleted domain and builds each new domain.
  5868. *
  5869. * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
  5870. * The masks don't intersect (don't overlap.) We should setup one
  5871. * sched domain for each mask. CPUs not in any of the cpumasks will
  5872. * not be load balanced. If the same cpumask appears both in the
  5873. * current 'doms_cur' domains and in the new 'doms_new', we can leave
  5874. * it as it is.
  5875. *
  5876. * The passed in 'doms_new' should be allocated using
  5877. * alloc_sched_domains. This routine takes ownership of it and will
  5878. * free_sched_domains it when done with it. If the caller failed the
  5879. * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
  5880. * and partition_sched_domains() will fallback to the single partition
  5881. * 'fallback_doms', it also forces the domains to be rebuilt.
  5882. *
  5883. * If doms_new == NULL it will be replaced with cpu_online_mask.
  5884. * ndoms_new == 0 is a special case for destroying existing domains,
  5885. * and it will not create the default domain.
  5886. *
  5887. * Call with hotplug lock held
  5888. */
  5889. void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
  5890. struct sched_domain_attr *dattr_new)
  5891. {
  5892. int i, j, n;
  5893. int new_topology;
  5894. mutex_lock(&sched_domains_mutex);
  5895. /* always unregister in case we don't destroy any domains */
  5896. unregister_sched_domain_sysctl();
  5897. /* Let architecture update cpu core mappings. */
  5898. new_topology = arch_update_cpu_topology();
  5899. n = doms_new ? ndoms_new : 0;
  5900. /* Destroy deleted domains */
  5901. for (i = 0; i < ndoms_cur; i++) {
  5902. for (j = 0; j < n && !new_topology; j++) {
  5903. if (cpumask_equal(doms_cur[i], doms_new[j])
  5904. && dattrs_equal(dattr_cur, i, dattr_new, j))
  5905. goto match1;
  5906. }
  5907. /* no match - a current sched domain not in new doms_new[] */
  5908. detach_destroy_domains(doms_cur[i]);
  5909. match1:
  5910. ;
  5911. }
  5912. n = ndoms_cur;
  5913. if (doms_new == NULL) {
  5914. n = 0;
  5915. doms_new = &fallback_doms;
  5916. cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
  5917. WARN_ON_ONCE(dattr_new);
  5918. }
  5919. /* Build new domains */
  5920. for (i = 0; i < ndoms_new; i++) {
  5921. for (j = 0; j < n && !new_topology; j++) {
  5922. if (cpumask_equal(doms_new[i], doms_cur[j])
  5923. && dattrs_equal(dattr_new, i, dattr_cur, j))
  5924. goto match2;
  5925. }
  5926. /* no match - add a new doms_new */
  5927. build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL);
  5928. match2:
  5929. ;
  5930. }
  5931. /* Remember the new sched domains */
  5932. if (doms_cur != &fallback_doms)
  5933. free_sched_domains(doms_cur, ndoms_cur);
  5934. kfree(dattr_cur); /* kfree(NULL) is safe */
  5935. doms_cur = doms_new;
  5936. dattr_cur = dattr_new;
  5937. ndoms_cur = ndoms_new;
  5938. register_sched_domain_sysctl();
  5939. mutex_unlock(&sched_domains_mutex);
  5940. }
  5941. static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */
  5942. /*
  5943. * Update cpusets according to cpu_active mask. If cpusets are
  5944. * disabled, cpuset_update_active_cpus() becomes a simple wrapper
  5945. * around partition_sched_domains().
  5946. *
  5947. * If we come here as part of a suspend/resume, don't touch cpusets because we
  5948. * want to restore it back to its original state upon resume anyway.
  5949. */
  5950. static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
  5951. void *hcpu)
  5952. {
  5953. switch (action) {
  5954. case CPU_ONLINE_FROZEN:
  5955. case CPU_DOWN_FAILED_FROZEN:
  5956. /*
  5957. * num_cpus_frozen tracks how many CPUs are involved in suspend
  5958. * resume sequence. As long as this is not the last online
  5959. * operation in the resume sequence, just build a single sched
  5960. * domain, ignoring cpusets.
  5961. */
  5962. num_cpus_frozen--;
  5963. if (likely(num_cpus_frozen)) {
  5964. partition_sched_domains(1, NULL, NULL);
  5965. break;
  5966. }
  5967. /*
  5968. * This is the last CPU online operation. So fall through and
  5969. * restore the original sched domains by considering the
  5970. * cpuset configurations.
  5971. */
  5972. case CPU_ONLINE:
  5973. cpuset_update_active_cpus(true);
  5974. break;
  5975. default:
  5976. return NOTIFY_DONE;
  5977. }
  5978. return NOTIFY_OK;
  5979. }
  5980. static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
  5981. void *hcpu)
  5982. {
  5983. unsigned long flags;
  5984. long cpu = (long)hcpu;
  5985. struct dl_bw *dl_b;
  5986. bool overflow;
  5987. int cpus;
  5988. switch (action) {
  5989. case CPU_DOWN_PREPARE:
  5990. rcu_read_lock_sched();
  5991. dl_b = dl_bw_of(cpu);
  5992. raw_spin_lock_irqsave(&dl_b->lock, flags);
  5993. cpus = dl_bw_cpus(cpu);
  5994. overflow = __dl_overflow(dl_b, cpus, 0, 0);
  5995. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  5996. rcu_read_unlock_sched();
  5997. if (overflow)
  5998. return notifier_from_errno(-EBUSY);
  5999. cpuset_update_active_cpus(false);
  6000. break;
  6001. case CPU_DOWN_PREPARE_FROZEN:
  6002. num_cpus_frozen++;
  6003. partition_sched_domains(1, NULL, NULL);
  6004. break;
  6005. default:
  6006. return NOTIFY_DONE;
  6007. }
  6008. return NOTIFY_OK;
  6009. }
  6010. void __init sched_init_smp(void)
  6011. {
  6012. cpumask_var_t non_isolated_cpus;
  6013. alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
  6014. alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
  6015. sched_init_numa();
  6016. /*
  6017. * There's no userspace yet to cause hotplug operations; hence all the
  6018. * cpu masks are stable and all blatant races in the below code cannot
  6019. * happen.
  6020. */
  6021. mutex_lock(&sched_domains_mutex);
  6022. init_sched_domains(cpu_active_mask);
  6023. cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
  6024. if (cpumask_empty(non_isolated_cpus))
  6025. cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
  6026. mutex_unlock(&sched_domains_mutex);
  6027. hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE);
  6028. hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
  6029. hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
  6030. init_hrtick();
  6031. /* Move init over to a non-isolated CPU */
  6032. if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
  6033. BUG();
  6034. sched_init_granularity();
  6035. free_cpumask_var(non_isolated_cpus);
  6036. init_sched_rt_class();
  6037. init_sched_dl_class();
  6038. }
  6039. #else
  6040. void __init sched_init_smp(void)
  6041. {
  6042. sched_init_granularity();
  6043. }
  6044. #endif /* CONFIG_SMP */
  6045. const_debug unsigned int sysctl_timer_migration = 1;
  6046. int in_sched_functions(unsigned long addr)
  6047. {
  6048. return in_lock_functions(addr) ||
  6049. (addr >= (unsigned long)__sched_text_start
  6050. && addr < (unsigned long)__sched_text_end);
  6051. }
  6052. #ifdef CONFIG_CGROUP_SCHED
  6053. /*
  6054. * Default task group.
  6055. * Every task in system belongs to this group at bootup.
  6056. */
  6057. struct task_group root_task_group;
  6058. LIST_HEAD(task_groups);
  6059. #endif
  6060. DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
  6061. void __init sched_init(void)
  6062. {
  6063. int i, j;
  6064. unsigned long alloc_size = 0, ptr;
  6065. #ifdef CONFIG_FAIR_GROUP_SCHED
  6066. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  6067. #endif
  6068. #ifdef CONFIG_RT_GROUP_SCHED
  6069. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  6070. #endif
  6071. if (alloc_size) {
  6072. ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
  6073. #ifdef CONFIG_FAIR_GROUP_SCHED
  6074. root_task_group.se = (struct sched_entity **)ptr;
  6075. ptr += nr_cpu_ids * sizeof(void **);
  6076. root_task_group.cfs_rq = (struct cfs_rq **)ptr;
  6077. ptr += nr_cpu_ids * sizeof(void **);
  6078. #endif /* CONFIG_FAIR_GROUP_SCHED */
  6079. #ifdef CONFIG_RT_GROUP_SCHED
  6080. root_task_group.rt_se = (struct sched_rt_entity **)ptr;
  6081. ptr += nr_cpu_ids * sizeof(void **);
  6082. root_task_group.rt_rq = (struct rt_rq **)ptr;
  6083. ptr += nr_cpu_ids * sizeof(void **);
  6084. #endif /* CONFIG_RT_GROUP_SCHED */
  6085. }
  6086. #ifdef CONFIG_CPUMASK_OFFSTACK
  6087. for_each_possible_cpu(i) {
  6088. per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
  6089. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  6090. }
  6091. #endif /* CONFIG_CPUMASK_OFFSTACK */
  6092. init_rt_bandwidth(&def_rt_bandwidth,
  6093. global_rt_period(), global_rt_runtime());
  6094. init_dl_bandwidth(&def_dl_bandwidth,
  6095. global_rt_period(), global_rt_runtime());
  6096. #ifdef CONFIG_SMP
  6097. init_defrootdomain();
  6098. #endif
  6099. #ifdef CONFIG_RT_GROUP_SCHED
  6100. init_rt_bandwidth(&root_task_group.rt_bandwidth,
  6101. global_rt_period(), global_rt_runtime());
  6102. #endif /* CONFIG_RT_GROUP_SCHED */
  6103. #ifdef CONFIG_CGROUP_SCHED
  6104. list_add(&root_task_group.list, &task_groups);
  6105. INIT_LIST_HEAD(&root_task_group.children);
  6106. INIT_LIST_HEAD(&root_task_group.siblings);
  6107. autogroup_init(&init_task);
  6108. #endif /* CONFIG_CGROUP_SCHED */
  6109. for_each_possible_cpu(i) {
  6110. struct rq *rq;
  6111. rq = cpu_rq(i);
  6112. raw_spin_lock_init(&rq->lock);
  6113. rq->nr_running = 0;
  6114. rq->calc_load_active = 0;
  6115. rq->calc_load_update = jiffies + LOAD_FREQ;
  6116. init_cfs_rq(&rq->cfs);
  6117. init_rt_rq(&rq->rt);
  6118. init_dl_rq(&rq->dl);
  6119. #ifdef CONFIG_FAIR_GROUP_SCHED
  6120. root_task_group.shares = ROOT_TASK_GROUP_LOAD;
  6121. INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
  6122. /*
  6123. * How much cpu bandwidth does root_task_group get?
  6124. *
  6125. * In case of task-groups formed thr' the cgroup filesystem, it
  6126. * gets 100% of the cpu resources in the system. This overall
  6127. * system cpu resource is divided among the tasks of
  6128. * root_task_group and its child task-groups in a fair manner,
  6129. * based on each entity's (task or task-group's) weight
  6130. * (se->load.weight).
  6131. *
  6132. * In other words, if root_task_group has 10 tasks of weight
  6133. * 1024) and two child groups A0 and A1 (of weight 1024 each),
  6134. * then A0's share of the cpu resource is:
  6135. *
  6136. * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
  6137. *
  6138. * We achieve this by letting root_task_group's tasks sit
  6139. * directly in rq->cfs (i.e root_task_group->se[] = NULL).
  6140. */
  6141. init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
  6142. init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
  6143. #endif /* CONFIG_FAIR_GROUP_SCHED */
  6144. rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
  6145. #ifdef CONFIG_RT_GROUP_SCHED
  6146. init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
  6147. #endif
  6148. for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
  6149. rq->cpu_load[j] = 0;
  6150. rq->last_load_update_tick = jiffies;
  6151. #ifdef CONFIG_SMP
  6152. rq->sd = NULL;
  6153. rq->rd = NULL;
  6154. rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
  6155. rq->post_schedule = 0;
  6156. rq->active_balance = 0;
  6157. rq->next_balance = jiffies;
  6158. rq->push_cpu = 0;
  6159. rq->cpu = i;
  6160. rq->online = 0;
  6161. rq->idle_stamp = 0;
  6162. rq->avg_idle = 2*sysctl_sched_migration_cost;
  6163. rq->max_idle_balance_cost = sysctl_sched_migration_cost;
  6164. INIT_LIST_HEAD(&rq->cfs_tasks);
  6165. rq_attach_root(rq, &def_root_domain);
  6166. #ifdef CONFIG_NO_HZ_COMMON
  6167. rq->nohz_flags = 0;
  6168. #endif
  6169. #ifdef CONFIG_NO_HZ_FULL
  6170. rq->last_sched_tick = 0;
  6171. #endif
  6172. #endif
  6173. init_rq_hrtick(rq);
  6174. atomic_set(&rq->nr_iowait, 0);
  6175. }
  6176. set_load_weight(&init_task);
  6177. #ifdef CONFIG_PREEMPT_NOTIFIERS
  6178. INIT_HLIST_HEAD(&init_task.preempt_notifiers);
  6179. #endif
  6180. /*
  6181. * The boot idle thread does lazy MMU switching as well:
  6182. */
  6183. atomic_inc(&init_mm.mm_count);
  6184. enter_lazy_tlb(&init_mm, current);
  6185. /*
  6186. * During early bootup we pretend to be a normal task:
  6187. */
  6188. current->sched_class = &fair_sched_class;
  6189. /*
  6190. * Make us the idle thread. Technically, schedule() should not be
  6191. * called from this thread, however somewhere below it might be,
  6192. * but because we are the idle thread, we just pick up running again
  6193. * when this runqueue becomes "idle".
  6194. */
  6195. init_idle(current, smp_processor_id());
  6196. calc_load_update = jiffies + LOAD_FREQ;
  6197. #ifdef CONFIG_SMP
  6198. zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT);
  6199. /* May be allocated at isolcpus cmdline parse time */
  6200. if (cpu_isolated_map == NULL)
  6201. zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
  6202. idle_thread_set_boot_cpu();
  6203. set_cpu_rq_start_time();
  6204. #endif
  6205. init_sched_fair_class();
  6206. scheduler_running = 1;
  6207. }
  6208. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  6209. static inline int preempt_count_equals(int preempt_offset)
  6210. {
  6211. int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
  6212. return (nested == preempt_offset);
  6213. }
  6214. void __might_sleep(const char *file, int line, int preempt_offset)
  6215. {
  6216. /*
  6217. * Blocking primitives will set (and therefore destroy) current->state,
  6218. * since we will exit with TASK_RUNNING make sure we enter with it,
  6219. * otherwise we will destroy state.
  6220. */
  6221. WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
  6222. "do not call blocking ops when !TASK_RUNNING; "
  6223. "state=%lx set at [<%p>] %pS\n",
  6224. current->state,
  6225. (void *)current->task_state_change,
  6226. (void *)current->task_state_change);
  6227. ___might_sleep(file, line, preempt_offset);
  6228. }
  6229. EXPORT_SYMBOL(__might_sleep);
  6230. void ___might_sleep(const char *file, int line, int preempt_offset)
  6231. {
  6232. static unsigned long prev_jiffy; /* ratelimiting */
  6233. rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */
  6234. if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
  6235. !is_idle_task(current)) ||
  6236. system_state != SYSTEM_RUNNING || oops_in_progress)
  6237. return;
  6238. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  6239. return;
  6240. prev_jiffy = jiffies;
  6241. printk(KERN_ERR
  6242. "BUG: sleeping function called from invalid context at %s:%d\n",
  6243. file, line);
  6244. printk(KERN_ERR
  6245. "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
  6246. in_atomic(), irqs_disabled(),
  6247. current->pid, current->comm);
  6248. if (task_stack_end_corrupted(current))
  6249. printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
  6250. debug_show_held_locks(current);
  6251. if (irqs_disabled())
  6252. print_irqtrace_events(current);
  6253. #ifdef CONFIG_DEBUG_PREEMPT
  6254. if (!preempt_count_equals(preempt_offset)) {
  6255. pr_err("Preemption disabled at:");
  6256. print_ip_sym(current->preempt_disable_ip);
  6257. pr_cont("\n");
  6258. }
  6259. #endif
  6260. dump_stack();
  6261. }
  6262. EXPORT_SYMBOL(___might_sleep);
  6263. #endif
  6264. #ifdef CONFIG_MAGIC_SYSRQ
  6265. static void normalize_task(struct rq *rq, struct task_struct *p)
  6266. {
  6267. const struct sched_class *prev_class = p->sched_class;
  6268. struct sched_attr attr = {
  6269. .sched_policy = SCHED_NORMAL,
  6270. };
  6271. int old_prio = p->prio;
  6272. int queued;
  6273. queued = task_on_rq_queued(p);
  6274. if (queued)
  6275. dequeue_task(rq, p, 0);
  6276. __setscheduler(rq, p, &attr, false);
  6277. if (queued) {
  6278. enqueue_task(rq, p, 0);
  6279. resched_curr(rq);
  6280. }
  6281. check_class_changed(rq, p, prev_class, old_prio);
  6282. }
  6283. void normalize_rt_tasks(void)
  6284. {
  6285. struct task_struct *g, *p;
  6286. unsigned long flags;
  6287. struct rq *rq;
  6288. read_lock(&tasklist_lock);
  6289. for_each_process_thread(g, p) {
  6290. /*
  6291. * Only normalize user tasks:
  6292. */
  6293. if (p->flags & PF_KTHREAD)
  6294. continue;
  6295. p->se.exec_start = 0;
  6296. #ifdef CONFIG_SCHEDSTATS
  6297. p->se.statistics.wait_start = 0;
  6298. p->se.statistics.sleep_start = 0;
  6299. p->se.statistics.block_start = 0;
  6300. #endif
  6301. if (!dl_task(p) && !rt_task(p)) {
  6302. /*
  6303. * Renice negative nice level userspace
  6304. * tasks back to 0:
  6305. */
  6306. if (task_nice(p) < 0)
  6307. set_user_nice(p, 0);
  6308. continue;
  6309. }
  6310. rq = task_rq_lock(p, &flags);
  6311. normalize_task(rq, p);
  6312. task_rq_unlock(rq, p, &flags);
  6313. }
  6314. read_unlock(&tasklist_lock);
  6315. }
  6316. #endif /* CONFIG_MAGIC_SYSRQ */
  6317. #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
  6318. /*
  6319. * These functions are only useful for the IA64 MCA handling, or kdb.
  6320. *
  6321. * They can only be called when the whole system has been
  6322. * stopped - every CPU needs to be quiescent, and no scheduling
  6323. * activity can take place. Using them for anything else would
  6324. * be a serious bug, and as a result, they aren't even visible
  6325. * under any other configuration.
  6326. */
  6327. /**
  6328. * curr_task - return the current task for a given cpu.
  6329. * @cpu: the processor in question.
  6330. *
  6331. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6332. *
  6333. * Return: The current task for @cpu.
  6334. */
  6335. struct task_struct *curr_task(int cpu)
  6336. {
  6337. return cpu_curr(cpu);
  6338. }
  6339. #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
  6340. #ifdef CONFIG_IA64
  6341. /**
  6342. * set_curr_task - set the current task for a given cpu.
  6343. * @cpu: the processor in question.
  6344. * @p: the task pointer to set.
  6345. *
  6346. * Description: This function must only be used when non-maskable interrupts
  6347. * are serviced on a separate stack. It allows the architecture to switch the
  6348. * notion of the current task on a cpu in a non-blocking manner. This function
  6349. * must be called with all CPU's synchronized, and interrupts disabled, the
  6350. * and caller must save the original value of the current task (see
  6351. * curr_task() above) and restore that value before reenabling interrupts and
  6352. * re-starting the system.
  6353. *
  6354. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  6355. */
  6356. void set_curr_task(int cpu, struct task_struct *p)
  6357. {
  6358. cpu_curr(cpu) = p;
  6359. }
  6360. #endif
  6361. #ifdef CONFIG_CGROUP_SCHED
  6362. /* task_group_lock serializes the addition/removal of task groups */
  6363. static DEFINE_SPINLOCK(task_group_lock);
  6364. static void free_sched_group(struct task_group *tg)
  6365. {
  6366. free_fair_sched_group(tg);
  6367. free_rt_sched_group(tg);
  6368. autogroup_free(tg);
  6369. kfree(tg);
  6370. }
  6371. /* allocate runqueue etc for a new task group */
  6372. struct task_group *sched_create_group(struct task_group *parent)
  6373. {
  6374. struct task_group *tg;
  6375. tg = kzalloc(sizeof(*tg), GFP_KERNEL);
  6376. if (!tg)
  6377. return ERR_PTR(-ENOMEM);
  6378. if (!alloc_fair_sched_group(tg, parent))
  6379. goto err;
  6380. if (!alloc_rt_sched_group(tg, parent))
  6381. goto err;
  6382. return tg;
  6383. err:
  6384. free_sched_group(tg);
  6385. return ERR_PTR(-ENOMEM);
  6386. }
  6387. void sched_online_group(struct task_group *tg, struct task_group *parent)
  6388. {
  6389. unsigned long flags;
  6390. spin_lock_irqsave(&task_group_lock, flags);
  6391. list_add_rcu(&tg->list, &task_groups);
  6392. WARN_ON(!parent); /* root should already exist */
  6393. tg->parent = parent;
  6394. INIT_LIST_HEAD(&tg->children);
  6395. list_add_rcu(&tg->siblings, &parent->children);
  6396. spin_unlock_irqrestore(&task_group_lock, flags);
  6397. }
  6398. /* rcu callback to free various structures associated with a task group */
  6399. static void free_sched_group_rcu(struct rcu_head *rhp)
  6400. {
  6401. /* now it should be safe to free those cfs_rqs */
  6402. free_sched_group(container_of(rhp, struct task_group, rcu));
  6403. }
  6404. /* Destroy runqueue etc associated with a task group */
  6405. void sched_destroy_group(struct task_group *tg)
  6406. {
  6407. /* wait for possible concurrent references to cfs_rqs complete */
  6408. call_rcu(&tg->rcu, free_sched_group_rcu);
  6409. }
  6410. void sched_offline_group(struct task_group *tg)
  6411. {
  6412. unsigned long flags;
  6413. int i;
  6414. /* end participation in shares distribution */
  6415. for_each_possible_cpu(i)
  6416. unregister_fair_sched_group(tg, i);
  6417. spin_lock_irqsave(&task_group_lock, flags);
  6418. list_del_rcu(&tg->list);
  6419. list_del_rcu(&tg->siblings);
  6420. spin_unlock_irqrestore(&task_group_lock, flags);
  6421. }
  6422. /* change task's runqueue when it moves between groups.
  6423. * The caller of this function should have put the task in its new group
  6424. * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
  6425. * reflect its new group.
  6426. */
  6427. void sched_move_task(struct task_struct *tsk)
  6428. {
  6429. struct task_group *tg;
  6430. int queued, running;
  6431. unsigned long flags;
  6432. struct rq *rq;
  6433. rq = task_rq_lock(tsk, &flags);
  6434. running = task_current(rq, tsk);
  6435. queued = task_on_rq_queued(tsk);
  6436. if (queued)
  6437. dequeue_task(rq, tsk, 0);
  6438. if (unlikely(running))
  6439. put_prev_task(rq, tsk);
  6440. /*
  6441. * All callers are synchronized by task_rq_lock(); we do not use RCU
  6442. * which is pointless here. Thus, we pass "true" to task_css_check()
  6443. * to prevent lockdep warnings.
  6444. */
  6445. tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
  6446. struct task_group, css);
  6447. tg = autogroup_task_group(tsk, tg);
  6448. tsk->sched_task_group = tg;
  6449. #ifdef CONFIG_FAIR_GROUP_SCHED
  6450. if (tsk->sched_class->task_move_group)
  6451. tsk->sched_class->task_move_group(tsk, queued);
  6452. else
  6453. #endif
  6454. set_task_rq(tsk, task_cpu(tsk));
  6455. if (unlikely(running))
  6456. tsk->sched_class->set_curr_task(rq);
  6457. if (queued)
  6458. enqueue_task(rq, tsk, 0);
  6459. task_rq_unlock(rq, tsk, &flags);
  6460. }
  6461. #endif /* CONFIG_CGROUP_SCHED */
  6462. #ifdef CONFIG_RT_GROUP_SCHED
  6463. /*
  6464. * Ensure that the real time constraints are schedulable.
  6465. */
  6466. static DEFINE_MUTEX(rt_constraints_mutex);
  6467. /* Must be called with tasklist_lock held */
  6468. static inline int tg_has_rt_tasks(struct task_group *tg)
  6469. {
  6470. struct task_struct *g, *p;
  6471. /*
  6472. * Autogroups do not have RT tasks; see autogroup_create().
  6473. */
  6474. if (task_group_is_autogroup(tg))
  6475. return 0;
  6476. for_each_process_thread(g, p) {
  6477. if (rt_task(p) && task_group(p) == tg)
  6478. return 1;
  6479. }
  6480. return 0;
  6481. }
  6482. struct rt_schedulable_data {
  6483. struct task_group *tg;
  6484. u64 rt_period;
  6485. u64 rt_runtime;
  6486. };
  6487. static int tg_rt_schedulable(struct task_group *tg, void *data)
  6488. {
  6489. struct rt_schedulable_data *d = data;
  6490. struct task_group *child;
  6491. unsigned long total, sum = 0;
  6492. u64 period, runtime;
  6493. period = ktime_to_ns(tg->rt_bandwidth.rt_period);
  6494. runtime = tg->rt_bandwidth.rt_runtime;
  6495. if (tg == d->tg) {
  6496. period = d->rt_period;
  6497. runtime = d->rt_runtime;
  6498. }
  6499. /*
  6500. * Cannot have more runtime than the period.
  6501. */
  6502. if (runtime > period && runtime != RUNTIME_INF)
  6503. return -EINVAL;
  6504. /*
  6505. * Ensure we don't starve existing RT tasks.
  6506. */
  6507. if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
  6508. return -EBUSY;
  6509. total = to_ratio(period, runtime);
  6510. /*
  6511. * Nobody can have more than the global setting allows.
  6512. */
  6513. if (total > to_ratio(global_rt_period(), global_rt_runtime()))
  6514. return -EINVAL;
  6515. /*
  6516. * The sum of our children's runtime should not exceed our own.
  6517. */
  6518. list_for_each_entry_rcu(child, &tg->children, siblings) {
  6519. period = ktime_to_ns(child->rt_bandwidth.rt_period);
  6520. runtime = child->rt_bandwidth.rt_runtime;
  6521. if (child == d->tg) {
  6522. period = d->rt_period;
  6523. runtime = d->rt_runtime;
  6524. }
  6525. sum += to_ratio(period, runtime);
  6526. }
  6527. if (sum > total)
  6528. return -EINVAL;
  6529. return 0;
  6530. }
  6531. static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
  6532. {
  6533. int ret;
  6534. struct rt_schedulable_data data = {
  6535. .tg = tg,
  6536. .rt_period = period,
  6537. .rt_runtime = runtime,
  6538. };
  6539. rcu_read_lock();
  6540. ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data);
  6541. rcu_read_unlock();
  6542. return ret;
  6543. }
  6544. static int tg_set_rt_bandwidth(struct task_group *tg,
  6545. u64 rt_period, u64 rt_runtime)
  6546. {
  6547. int i, err = 0;
  6548. /*
  6549. * Disallowing the root group RT runtime is BAD, it would disallow the
  6550. * kernel creating (and or operating) RT threads.
  6551. */
  6552. if (tg == &root_task_group && rt_runtime == 0)
  6553. return -EINVAL;
  6554. /* No period doesn't make any sense. */
  6555. if (rt_period == 0)
  6556. return -EINVAL;
  6557. mutex_lock(&rt_constraints_mutex);
  6558. read_lock(&tasklist_lock);
  6559. err = __rt_schedulable(tg, rt_period, rt_runtime);
  6560. if (err)
  6561. goto unlock;
  6562. raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
  6563. tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
  6564. tg->rt_bandwidth.rt_runtime = rt_runtime;
  6565. for_each_possible_cpu(i) {
  6566. struct rt_rq *rt_rq = tg->rt_rq[i];
  6567. raw_spin_lock(&rt_rq->rt_runtime_lock);
  6568. rt_rq->rt_runtime = rt_runtime;
  6569. raw_spin_unlock(&rt_rq->rt_runtime_lock);
  6570. }
  6571. raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
  6572. unlock:
  6573. read_unlock(&tasklist_lock);
  6574. mutex_unlock(&rt_constraints_mutex);
  6575. return err;
  6576. }
  6577. static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
  6578. {
  6579. u64 rt_runtime, rt_period;
  6580. rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
  6581. rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
  6582. if (rt_runtime_us < 0)
  6583. rt_runtime = RUNTIME_INF;
  6584. return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
  6585. }
  6586. static long sched_group_rt_runtime(struct task_group *tg)
  6587. {
  6588. u64 rt_runtime_us;
  6589. if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
  6590. return -1;
  6591. rt_runtime_us = tg->rt_bandwidth.rt_runtime;
  6592. do_div(rt_runtime_us, NSEC_PER_USEC);
  6593. return rt_runtime_us;
  6594. }
  6595. static int sched_group_set_rt_period(struct task_group *tg, u64 rt_period_us)
  6596. {
  6597. u64 rt_runtime, rt_period;
  6598. rt_period = rt_period_us * NSEC_PER_USEC;
  6599. rt_runtime = tg->rt_bandwidth.rt_runtime;
  6600. return tg_set_rt_bandwidth(tg, rt_period, rt_runtime);
  6601. }
  6602. static long sched_group_rt_period(struct task_group *tg)
  6603. {
  6604. u64 rt_period_us;
  6605. rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
  6606. do_div(rt_period_us, NSEC_PER_USEC);
  6607. return rt_period_us;
  6608. }
  6609. #endif /* CONFIG_RT_GROUP_SCHED */
  6610. #ifdef CONFIG_RT_GROUP_SCHED
  6611. static int sched_rt_global_constraints(void)
  6612. {
  6613. int ret = 0;
  6614. mutex_lock(&rt_constraints_mutex);
  6615. read_lock(&tasklist_lock);
  6616. ret = __rt_schedulable(NULL, 0, 0);
  6617. read_unlock(&tasklist_lock);
  6618. mutex_unlock(&rt_constraints_mutex);
  6619. return ret;
  6620. }
  6621. static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
  6622. {
  6623. /* Don't accept realtime tasks when there is no way for them to run */
  6624. if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
  6625. return 0;
  6626. return 1;
  6627. }
  6628. #else /* !CONFIG_RT_GROUP_SCHED */
  6629. static int sched_rt_global_constraints(void)
  6630. {
  6631. unsigned long flags;
  6632. int i, ret = 0;
  6633. raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
  6634. for_each_possible_cpu(i) {
  6635. struct rt_rq *rt_rq = &cpu_rq(i)->rt;
  6636. raw_spin_lock(&rt_rq->rt_runtime_lock);
  6637. rt_rq->rt_runtime = global_rt_runtime();
  6638. raw_spin_unlock(&rt_rq->rt_runtime_lock);
  6639. }
  6640. raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
  6641. return ret;
  6642. }
  6643. #endif /* CONFIG_RT_GROUP_SCHED */
  6644. static int sched_dl_global_validate(void)
  6645. {
  6646. u64 runtime = global_rt_runtime();
  6647. u64 period = global_rt_period();
  6648. u64 new_bw = to_ratio(period, runtime);
  6649. struct dl_bw *dl_b;
  6650. int cpu, ret = 0;
  6651. unsigned long flags;
  6652. /*
  6653. * Here we want to check the bandwidth not being set to some
  6654. * value smaller than the currently allocated bandwidth in
  6655. * any of the root_domains.
  6656. *
  6657. * FIXME: Cycling on all the CPUs is overdoing, but simpler than
  6658. * cycling on root_domains... Discussion on different/better
  6659. * solutions is welcome!
  6660. */
  6661. for_each_possible_cpu(cpu) {
  6662. rcu_read_lock_sched();
  6663. dl_b = dl_bw_of(cpu);
  6664. raw_spin_lock_irqsave(&dl_b->lock, flags);
  6665. if (new_bw < dl_b->total_bw)
  6666. ret = -EBUSY;
  6667. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  6668. rcu_read_unlock_sched();
  6669. if (ret)
  6670. break;
  6671. }
  6672. return ret;
  6673. }
  6674. static void sched_dl_do_global(void)
  6675. {
  6676. u64 new_bw = -1;
  6677. struct dl_bw *dl_b;
  6678. int cpu;
  6679. unsigned long flags;
  6680. def_dl_bandwidth.dl_period = global_rt_period();
  6681. def_dl_bandwidth.dl_runtime = global_rt_runtime();
  6682. if (global_rt_runtime() != RUNTIME_INF)
  6683. new_bw = to_ratio(global_rt_period(), global_rt_runtime());
  6684. /*
  6685. * FIXME: As above...
  6686. */
  6687. for_each_possible_cpu(cpu) {
  6688. rcu_read_lock_sched();
  6689. dl_b = dl_bw_of(cpu);
  6690. raw_spin_lock_irqsave(&dl_b->lock, flags);
  6691. dl_b->bw = new_bw;
  6692. raw_spin_unlock_irqrestore(&dl_b->lock, flags);
  6693. rcu_read_unlock_sched();
  6694. }
  6695. }
  6696. static int sched_rt_global_validate(void)
  6697. {
  6698. if (sysctl_sched_rt_period <= 0)
  6699. return -EINVAL;
  6700. if ((sysctl_sched_rt_runtime != RUNTIME_INF) &&
  6701. (sysctl_sched_rt_runtime > sysctl_sched_rt_period))
  6702. return -EINVAL;
  6703. return 0;
  6704. }
  6705. static void sched_rt_do_global(void)
  6706. {
  6707. def_rt_bandwidth.rt_runtime = global_rt_runtime();
  6708. def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period());
  6709. }
  6710. int sched_rt_handler(struct ctl_table *table, int write,
  6711. void __user *buffer, size_t *lenp,
  6712. loff_t *ppos)
  6713. {
  6714. int old_period, old_runtime;
  6715. static DEFINE_MUTEX(mutex);
  6716. int ret;
  6717. mutex_lock(&mutex);
  6718. old_period = sysctl_sched_rt_period;
  6719. old_runtime = sysctl_sched_rt_runtime;
  6720. ret = proc_dointvec(table, write, buffer, lenp, ppos);
  6721. if (!ret && write) {
  6722. ret = sched_rt_global_validate();
  6723. if (ret)
  6724. goto undo;
  6725. ret = sched_dl_global_validate();
  6726. if (ret)
  6727. goto undo;
  6728. ret = sched_rt_global_constraints();
  6729. if (ret)
  6730. goto undo;
  6731. sched_rt_do_global();
  6732. sched_dl_do_global();
  6733. }
  6734. if (0) {
  6735. undo:
  6736. sysctl_sched_rt_period = old_period;
  6737. sysctl_sched_rt_runtime = old_runtime;
  6738. }
  6739. mutex_unlock(&mutex);
  6740. return ret;
  6741. }
  6742. int sched_rr_handler(struct ctl_table *table, int write,
  6743. void __user *buffer, size_t *lenp,
  6744. loff_t *ppos)
  6745. {
  6746. int ret;
  6747. static DEFINE_MUTEX(mutex);
  6748. mutex_lock(&mutex);
  6749. ret = proc_dointvec(table, write, buffer, lenp, ppos);
  6750. /* make sure that internally we keep jiffies */
  6751. /* also, writing zero resets timeslice to default */
  6752. if (!ret && write) {
  6753. sched_rr_timeslice = sched_rr_timeslice <= 0 ?
  6754. RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice);
  6755. }
  6756. mutex_unlock(&mutex);
  6757. return ret;
  6758. }
  6759. #ifdef CONFIG_CGROUP_SCHED
  6760. static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
  6761. {
  6762. return css ? container_of(css, struct task_group, css) : NULL;
  6763. }
  6764. static struct cgroup_subsys_state *
  6765. cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  6766. {
  6767. struct task_group *parent = css_tg(parent_css);
  6768. struct task_group *tg;
  6769. if (!parent) {
  6770. /* This is early initialization for the top cgroup */
  6771. return &root_task_group.css;
  6772. }
  6773. tg = sched_create_group(parent);
  6774. if (IS_ERR(tg))
  6775. return ERR_PTR(-ENOMEM);
  6776. return &tg->css;
  6777. }
  6778. static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
  6779. {
  6780. struct task_group *tg = css_tg(css);
  6781. struct task_group *parent = css_tg(css->parent);
  6782. if (parent)
  6783. sched_online_group(tg, parent);
  6784. return 0;
  6785. }
  6786. static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
  6787. {
  6788. struct task_group *tg = css_tg(css);
  6789. sched_destroy_group(tg);
  6790. }
  6791. static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css)
  6792. {
  6793. struct task_group *tg = css_tg(css);
  6794. sched_offline_group(tg);
  6795. }
  6796. static void cpu_cgroup_fork(struct task_struct *task)
  6797. {
  6798. sched_move_task(task);
  6799. }
  6800. static int cpu_cgroup_can_attach(struct cgroup_subsys_state *css,
  6801. struct cgroup_taskset *tset)
  6802. {
  6803. struct task_struct *task;
  6804. cgroup_taskset_for_each(task, tset) {
  6805. #ifdef CONFIG_RT_GROUP_SCHED
  6806. if (!sched_rt_can_attach(css_tg(css), task))
  6807. return -EINVAL;
  6808. #else
  6809. /* We don't support RT-tasks being in separate groups */
  6810. if (task->sched_class != &fair_sched_class)
  6811. return -EINVAL;
  6812. #endif
  6813. }
  6814. return 0;
  6815. }
  6816. static void cpu_cgroup_attach(struct cgroup_subsys_state *css,
  6817. struct cgroup_taskset *tset)
  6818. {
  6819. struct task_struct *task;
  6820. cgroup_taskset_for_each(task, tset)
  6821. sched_move_task(task);
  6822. }
  6823. static void cpu_cgroup_exit(struct cgroup_subsys_state *css,
  6824. struct cgroup_subsys_state *old_css,
  6825. struct task_struct *task)
  6826. {
  6827. /*
  6828. * cgroup_exit() is called in the copy_process() failure path.
  6829. * Ignore this case since the task hasn't ran yet, this avoids
  6830. * trying to poke a half freed task state from generic code.
  6831. */
  6832. if (!(task->flags & PF_EXITING))
  6833. return;
  6834. sched_move_task(task);
  6835. }
  6836. #ifdef CONFIG_FAIR_GROUP_SCHED
  6837. static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
  6838. struct cftype *cftype, u64 shareval)
  6839. {
  6840. return sched_group_set_shares(css_tg(css), scale_load(shareval));
  6841. }
  6842. static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
  6843. struct cftype *cft)
  6844. {
  6845. struct task_group *tg = css_tg(css);
  6846. return (u64) scale_load_down(tg->shares);
  6847. }
  6848. #ifdef CONFIG_CFS_BANDWIDTH
  6849. static DEFINE_MUTEX(cfs_constraints_mutex);
  6850. const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
  6851. const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
  6852. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
  6853. static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
  6854. {
  6855. int i, ret = 0, runtime_enabled, runtime_was_enabled;
  6856. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  6857. if (tg == &root_task_group)
  6858. return -EINVAL;
  6859. /*
  6860. * Ensure we have at some amount of bandwidth every period. This is
  6861. * to prevent reaching a state of large arrears when throttled via
  6862. * entity_tick() resulting in prolonged exit starvation.
  6863. */
  6864. if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
  6865. return -EINVAL;
  6866. /*
  6867. * Likewise, bound things on the otherside by preventing insane quota
  6868. * periods. This also allows us to normalize in computing quota
  6869. * feasibility.
  6870. */
  6871. if (period > max_cfs_quota_period)
  6872. return -EINVAL;
  6873. /*
  6874. * Prevent race between setting of cfs_rq->runtime_enabled and
  6875. * unthrottle_offline_cfs_rqs().
  6876. */
  6877. get_online_cpus();
  6878. mutex_lock(&cfs_constraints_mutex);
  6879. ret = __cfs_schedulable(tg, period, quota);
  6880. if (ret)
  6881. goto out_unlock;
  6882. runtime_enabled = quota != RUNTIME_INF;
  6883. runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
  6884. /*
  6885. * If we need to toggle cfs_bandwidth_used, off->on must occur
  6886. * before making related changes, and on->off must occur afterwards
  6887. */
  6888. if (runtime_enabled && !runtime_was_enabled)
  6889. cfs_bandwidth_usage_inc();
  6890. raw_spin_lock_irq(&cfs_b->lock);
  6891. cfs_b->period = ns_to_ktime(period);
  6892. cfs_b->quota = quota;
  6893. __refill_cfs_bandwidth_runtime(cfs_b);
  6894. /* restart the period timer (if active) to handle new period expiry */
  6895. if (runtime_enabled && cfs_b->timer_active) {
  6896. /* force a reprogram */
  6897. __start_cfs_bandwidth(cfs_b, true);
  6898. }
  6899. raw_spin_unlock_irq(&cfs_b->lock);
  6900. for_each_online_cpu(i) {
  6901. struct cfs_rq *cfs_rq = tg->cfs_rq[i];
  6902. struct rq *rq = cfs_rq->rq;
  6903. raw_spin_lock_irq(&rq->lock);
  6904. cfs_rq->runtime_enabled = runtime_enabled;
  6905. cfs_rq->runtime_remaining = 0;
  6906. if (cfs_rq->throttled)
  6907. unthrottle_cfs_rq(cfs_rq);
  6908. raw_spin_unlock_irq(&rq->lock);
  6909. }
  6910. if (runtime_was_enabled && !runtime_enabled)
  6911. cfs_bandwidth_usage_dec();
  6912. out_unlock:
  6913. mutex_unlock(&cfs_constraints_mutex);
  6914. put_online_cpus();
  6915. return ret;
  6916. }
  6917. int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
  6918. {
  6919. u64 quota, period;
  6920. period = ktime_to_ns(tg->cfs_bandwidth.period);
  6921. if (cfs_quota_us < 0)
  6922. quota = RUNTIME_INF;
  6923. else
  6924. quota = (u64)cfs_quota_us * NSEC_PER_USEC;
  6925. return tg_set_cfs_bandwidth(tg, period, quota);
  6926. }
  6927. long tg_get_cfs_quota(struct task_group *tg)
  6928. {
  6929. u64 quota_us;
  6930. if (tg->cfs_bandwidth.quota == RUNTIME_INF)
  6931. return -1;
  6932. quota_us = tg->cfs_bandwidth.quota;
  6933. do_div(quota_us, NSEC_PER_USEC);
  6934. return quota_us;
  6935. }
  6936. int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
  6937. {
  6938. u64 quota, period;
  6939. period = (u64)cfs_period_us * NSEC_PER_USEC;
  6940. quota = tg->cfs_bandwidth.quota;
  6941. return tg_set_cfs_bandwidth(tg, period, quota);
  6942. }
  6943. long tg_get_cfs_period(struct task_group *tg)
  6944. {
  6945. u64 cfs_period_us;
  6946. cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
  6947. do_div(cfs_period_us, NSEC_PER_USEC);
  6948. return cfs_period_us;
  6949. }
  6950. static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
  6951. struct cftype *cft)
  6952. {
  6953. return tg_get_cfs_quota(css_tg(css));
  6954. }
  6955. static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
  6956. struct cftype *cftype, s64 cfs_quota_us)
  6957. {
  6958. return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
  6959. }
  6960. static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
  6961. struct cftype *cft)
  6962. {
  6963. return tg_get_cfs_period(css_tg(css));
  6964. }
  6965. static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
  6966. struct cftype *cftype, u64 cfs_period_us)
  6967. {
  6968. return tg_set_cfs_period(css_tg(css), cfs_period_us);
  6969. }
  6970. struct cfs_schedulable_data {
  6971. struct task_group *tg;
  6972. u64 period, quota;
  6973. };
  6974. /*
  6975. * normalize group quota/period to be quota/max_period
  6976. * note: units are usecs
  6977. */
  6978. static u64 normalize_cfs_quota(struct task_group *tg,
  6979. struct cfs_schedulable_data *d)
  6980. {
  6981. u64 quota, period;
  6982. if (tg == d->tg) {
  6983. period = d->period;
  6984. quota = d->quota;
  6985. } else {
  6986. period = tg_get_cfs_period(tg);
  6987. quota = tg_get_cfs_quota(tg);
  6988. }
  6989. /* note: these should typically be equivalent */
  6990. if (quota == RUNTIME_INF || quota == -1)
  6991. return RUNTIME_INF;
  6992. return to_ratio(period, quota);
  6993. }
  6994. static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
  6995. {
  6996. struct cfs_schedulable_data *d = data;
  6997. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  6998. s64 quota = 0, parent_quota = -1;
  6999. if (!tg->parent) {
  7000. quota = RUNTIME_INF;
  7001. } else {
  7002. struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
  7003. quota = normalize_cfs_quota(tg, d);
  7004. parent_quota = parent_b->hierarchical_quota;
  7005. /*
  7006. * ensure max(child_quota) <= parent_quota, inherit when no
  7007. * limit is set
  7008. */
  7009. if (quota == RUNTIME_INF)
  7010. quota = parent_quota;
  7011. else if (parent_quota != RUNTIME_INF && quota > parent_quota)
  7012. return -EINVAL;
  7013. }
  7014. cfs_b->hierarchical_quota = quota;
  7015. return 0;
  7016. }
  7017. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
  7018. {
  7019. int ret;
  7020. struct cfs_schedulable_data data = {
  7021. .tg = tg,
  7022. .period = period,
  7023. .quota = quota,
  7024. };
  7025. if (quota != RUNTIME_INF) {
  7026. do_div(data.period, NSEC_PER_USEC);
  7027. do_div(data.quota, NSEC_PER_USEC);
  7028. }
  7029. rcu_read_lock();
  7030. ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
  7031. rcu_read_unlock();
  7032. return ret;
  7033. }
  7034. static int cpu_stats_show(struct seq_file *sf, void *v)
  7035. {
  7036. struct task_group *tg = css_tg(seq_css(sf));
  7037. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  7038. seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
  7039. seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
  7040. seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
  7041. return 0;
  7042. }
  7043. #endif /* CONFIG_CFS_BANDWIDTH */
  7044. #endif /* CONFIG_FAIR_GROUP_SCHED */
  7045. #ifdef CONFIG_RT_GROUP_SCHED
  7046. static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
  7047. struct cftype *cft, s64 val)
  7048. {
  7049. return sched_group_set_rt_runtime(css_tg(css), val);
  7050. }
  7051. static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
  7052. struct cftype *cft)
  7053. {
  7054. return sched_group_rt_runtime(css_tg(css));
  7055. }
  7056. static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
  7057. struct cftype *cftype, u64 rt_period_us)
  7058. {
  7059. return sched_group_set_rt_period(css_tg(css), rt_period_us);
  7060. }
  7061. static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
  7062. struct cftype *cft)
  7063. {
  7064. return sched_group_rt_period(css_tg(css));
  7065. }
  7066. #endif /* CONFIG_RT_GROUP_SCHED */
  7067. static struct cftype cpu_files[] = {
  7068. #ifdef CONFIG_FAIR_GROUP_SCHED
  7069. {
  7070. .name = "shares",
  7071. .read_u64 = cpu_shares_read_u64,
  7072. .write_u64 = cpu_shares_write_u64,
  7073. },
  7074. #endif
  7075. #ifdef CONFIG_CFS_BANDWIDTH
  7076. {
  7077. .name = "cfs_quota_us",
  7078. .read_s64 = cpu_cfs_quota_read_s64,
  7079. .write_s64 = cpu_cfs_quota_write_s64,
  7080. },
  7081. {
  7082. .name = "cfs_period_us",
  7083. .read_u64 = cpu_cfs_period_read_u64,
  7084. .write_u64 = cpu_cfs_period_write_u64,
  7085. },
  7086. {
  7087. .name = "stat",
  7088. .seq_show = cpu_stats_show,
  7089. },
  7090. #endif
  7091. #ifdef CONFIG_RT_GROUP_SCHED
  7092. {
  7093. .name = "rt_runtime_us",
  7094. .read_s64 = cpu_rt_runtime_read,
  7095. .write_s64 = cpu_rt_runtime_write,
  7096. },
  7097. {
  7098. .name = "rt_period_us",
  7099. .read_u64 = cpu_rt_period_read_uint,
  7100. .write_u64 = cpu_rt_period_write_uint,
  7101. },
  7102. #endif
  7103. { } /* terminate */
  7104. };
  7105. struct cgroup_subsys cpu_cgrp_subsys = {
  7106. .css_alloc = cpu_cgroup_css_alloc,
  7107. .css_free = cpu_cgroup_css_free,
  7108. .css_online = cpu_cgroup_css_online,
  7109. .css_offline = cpu_cgroup_css_offline,
  7110. .fork = cpu_cgroup_fork,
  7111. .can_attach = cpu_cgroup_can_attach,
  7112. .attach = cpu_cgroup_attach,
  7113. .exit = cpu_cgroup_exit,
  7114. .legacy_cftypes = cpu_files,
  7115. .early_init = 1,
  7116. };
  7117. #endif /* CONFIG_CGROUP_SCHED */
  7118. void dump_cpu_task(int cpu)
  7119. {
  7120. pr_info("Task dump for CPU %d:\n", cpu);
  7121. sched_show_task(cpu_curr(cpu));
  7122. }