core.c 218 KB

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