core.c 208 KB

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