core.c 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087
  1. /*
  2. * kernel/sched/core.c
  3. *
  4. * Core kernel scheduler code and related syscalls
  5. *
  6. * Copyright (C) 1991-2002 Linus Torvalds
  7. */
  8. #include <linux/sched.h>
  9. #include <linux/sched/clock.h>
  10. #include <uapi/linux/sched/types.h>
  11. #include <linux/sched/loadavg.h>
  12. #include <linux/sched/hotplug.h>
  13. #include <linux/wait_bit.h>
  14. #include <linux/cpuset.h>
  15. #include <linux/delayacct.h>
  16. #include <linux/init_task.h>
  17. #include <linux/context_tracking.h>
  18. #include <linux/rcupdate_wait.h>
  19. #include <linux/compat.h>
  20. #include <linux/blkdev.h>
  21. #include <linux/kprobes.h>
  22. #include <linux/mmu_context.h>
  23. #include <linux/module.h>
  24. #include <linux/nmi.h>
  25. #include <linux/prefetch.h>
  26. #include <linux/profile.h>
  27. #include <linux/security.h>
  28. #include <linux/syscalls.h>
  29. #include <linux/sched/isolation.h>
  30. #include <asm/switch_to.h>
  31. #include <asm/tlb.h>
  32. #ifdef CONFIG_PARAVIRT
  33. #include <asm/paravirt.h>
  34. #endif
  35. #include "sched.h"
  36. #include "../workqueue_internal.h"
  37. #include "../smpboot.h"
  38. #define CREATE_TRACE_POINTS
  39. #include <trace/events/sched.h>
  40. DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
  41. #if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL)
  42. /*
  43. * Debugging: various feature bits
  44. *
  45. * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
  46. * sysctl_sched_features, defined in sched.h, to allow constants propagation
  47. * at compile time and compiler optimization based on features default.
  48. */
  49. #define SCHED_FEAT(name, enabled) \
  50. (1UL << __SCHED_FEAT_##name) * enabled |
  51. const_debug unsigned int sysctl_sched_features =
  52. #include "features.h"
  53. 0;
  54. #undef SCHED_FEAT
  55. #endif
  56. /*
  57. * Number of tasks to iterate in a single balance run.
  58. * Limited because this is done with IRQs disabled.
  59. */
  60. const_debug unsigned int sysctl_sched_nr_migrate = 32;
  61. /*
  62. * period over which we average the RT time consumption, measured
  63. * in ms.
  64. *
  65. * default: 1s
  66. */
  67. const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
  68. /*
  69. * period over which we measure -rt task CPU usage in us.
  70. * default: 1s
  71. */
  72. unsigned int sysctl_sched_rt_period = 1000000;
  73. __read_mostly int scheduler_running;
  74. /*
  75. * part of the period that we allow rt tasks to run in us.
  76. * default: 0.95s
  77. */
  78. int sysctl_sched_rt_runtime = 950000;
  79. /*
  80. * __task_rq_lock - lock the rq @p resides on.
  81. */
  82. struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  83. __acquires(rq->lock)
  84. {
  85. struct rq *rq;
  86. lockdep_assert_held(&p->pi_lock);
  87. for (;;) {
  88. rq = task_rq(p);
  89. raw_spin_lock(&rq->lock);
  90. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  91. rq_pin_lock(rq, rf);
  92. return rq;
  93. }
  94. raw_spin_unlock(&rq->lock);
  95. while (unlikely(task_on_rq_migrating(p)))
  96. cpu_relax();
  97. }
  98. }
  99. /*
  100. * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
  101. */
  102. struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
  103. __acquires(p->pi_lock)
  104. __acquires(rq->lock)
  105. {
  106. struct rq *rq;
  107. for (;;) {
  108. raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
  109. rq = task_rq(p);
  110. raw_spin_lock(&rq->lock);
  111. /*
  112. * move_queued_task() task_rq_lock()
  113. *
  114. * ACQUIRE (rq->lock)
  115. * [S] ->on_rq = MIGRATING [L] rq = task_rq()
  116. * WMB (__set_task_cpu()) ACQUIRE (rq->lock);
  117. * [S] ->cpu = new_cpu [L] task_rq()
  118. * [L] ->on_rq
  119. * RELEASE (rq->lock)
  120. *
  121. * If we observe the old cpu in task_rq_lock, the acquire of
  122. * the old rq->lock will fully serialize against the stores.
  123. *
  124. * If we observe the new CPU in task_rq_lock, the acquire will
  125. * pair with the WMB to ensure we must then also see migrating.
  126. */
  127. if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
  128. rq_pin_lock(rq, rf);
  129. return rq;
  130. }
  131. raw_spin_unlock(&rq->lock);
  132. raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
  133. while (unlikely(task_on_rq_migrating(p)))
  134. cpu_relax();
  135. }
  136. }
  137. /*
  138. * RQ-clock updating methods:
  139. */
  140. static void update_rq_clock_task(struct rq *rq, s64 delta)
  141. {
  142. /*
  143. * In theory, the compile should just see 0 here, and optimize out the call
  144. * to sched_rt_avg_update. But I don't trust it...
  145. */
  146. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  147. s64 steal = 0, irq_delta = 0;
  148. #endif
  149. #ifdef CONFIG_IRQ_TIME_ACCOUNTING
  150. irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
  151. /*
  152. * Since irq_time is only updated on {soft,}irq_exit, we might run into
  153. * this case when a previous update_rq_clock() happened inside a
  154. * {soft,}irq region.
  155. *
  156. * When this happens, we stop ->clock_task and only update the
  157. * prev_irq_time stamp to account for the part that fit, so that a next
  158. * update will consume the rest. This ensures ->clock_task is
  159. * monotonic.
  160. *
  161. * It does however cause some slight miss-attribution of {soft,}irq
  162. * time, a more accurate solution would be to update the irq_time using
  163. * the current rq->clock timestamp, except that would require using
  164. * atomic ops.
  165. */
  166. if (irq_delta > delta)
  167. irq_delta = delta;
  168. rq->prev_irq_time += irq_delta;
  169. delta -= irq_delta;
  170. #endif
  171. #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
  172. if (static_key_false((&paravirt_steal_rq_enabled))) {
  173. steal = paravirt_steal_clock(cpu_of(rq));
  174. steal -= rq->prev_steal_time_rq;
  175. if (unlikely(steal > delta))
  176. steal = delta;
  177. rq->prev_steal_time_rq += steal;
  178. delta -= steal;
  179. }
  180. #endif
  181. rq->clock_task += delta;
  182. #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
  183. if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
  184. sched_rt_avg_update(rq, irq_delta + steal);
  185. #endif
  186. }
  187. void update_rq_clock(struct rq *rq)
  188. {
  189. s64 delta;
  190. lockdep_assert_held(&rq->lock);
  191. if (rq->clock_update_flags & RQCF_ACT_SKIP)
  192. return;
  193. #ifdef CONFIG_SCHED_DEBUG
  194. if (sched_feat(WARN_DOUBLE_CLOCK))
  195. SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
  196. rq->clock_update_flags |= RQCF_UPDATED;
  197. #endif
  198. delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
  199. if (delta < 0)
  200. return;
  201. rq->clock += delta;
  202. update_rq_clock_task(rq, delta);
  203. }
  204. #ifdef CONFIG_SCHED_HRTICK
  205. /*
  206. * Use HR-timers to deliver accurate preemption points.
  207. */
  208. static void hrtick_clear(struct rq *rq)
  209. {
  210. if (hrtimer_active(&rq->hrtick_timer))
  211. hrtimer_cancel(&rq->hrtick_timer);
  212. }
  213. /*
  214. * High-resolution timer tick.
  215. * Runs from hardirq context with interrupts disabled.
  216. */
  217. static enum hrtimer_restart hrtick(struct hrtimer *timer)
  218. {
  219. struct rq *rq = container_of(timer, struct rq, hrtick_timer);
  220. struct rq_flags rf;
  221. WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
  222. rq_lock(rq, &rf);
  223. update_rq_clock(rq);
  224. rq->curr->sched_class->task_tick(rq, rq->curr, 1);
  225. rq_unlock(rq, &rf);
  226. return HRTIMER_NORESTART;
  227. }
  228. #ifdef CONFIG_SMP
  229. static void __hrtick_restart(struct rq *rq)
  230. {
  231. struct hrtimer *timer = &rq->hrtick_timer;
  232. hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
  233. }
  234. /*
  235. * called from hardirq (IPI) context
  236. */
  237. static void __hrtick_start(void *arg)
  238. {
  239. struct rq *rq = arg;
  240. struct rq_flags rf;
  241. rq_lock(rq, &rf);
  242. __hrtick_restart(rq);
  243. rq->hrtick_csd_pending = 0;
  244. rq_unlock(rq, &rf);
  245. }
  246. /*
  247. * Called to set the hrtick timer state.
  248. *
  249. * called with rq->lock held and irqs disabled
  250. */
  251. void hrtick_start(struct rq *rq, u64 delay)
  252. {
  253. struct hrtimer *timer = &rq->hrtick_timer;
  254. ktime_t time;
  255. s64 delta;
  256. /*
  257. * Don't schedule slices shorter than 10000ns, that just
  258. * doesn't make sense and can cause timer DoS.
  259. */
  260. delta = max_t(s64, delay, 10000LL);
  261. time = ktime_add_ns(timer->base->get_time(), delta);
  262. hrtimer_set_expires(timer, time);
  263. if (rq == this_rq()) {
  264. __hrtick_restart(rq);
  265. } else if (!rq->hrtick_csd_pending) {
  266. smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
  267. rq->hrtick_csd_pending = 1;
  268. }
  269. }
  270. #else
  271. /*
  272. * Called to set the hrtick timer state.
  273. *
  274. * called with rq->lock held and irqs disabled
  275. */
  276. void hrtick_start(struct rq *rq, u64 delay)
  277. {
  278. /*
  279. * Don't schedule slices shorter than 10000ns, that just
  280. * doesn't make sense. Rely on vruntime for fairness.
  281. */
  282. delay = max_t(u64, delay, 10000LL);
  283. hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
  284. HRTIMER_MODE_REL_PINNED);
  285. }
  286. #endif /* CONFIG_SMP */
  287. static void hrtick_rq_init(struct rq *rq)
  288. {
  289. #ifdef CONFIG_SMP
  290. rq->hrtick_csd_pending = 0;
  291. rq->hrtick_csd.flags = 0;
  292. rq->hrtick_csd.func = __hrtick_start;
  293. rq->hrtick_csd.info = rq;
  294. #endif
  295. hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
  296. rq->hrtick_timer.function = hrtick;
  297. }
  298. #else /* CONFIG_SCHED_HRTICK */
  299. static inline void hrtick_clear(struct rq *rq)
  300. {
  301. }
  302. static inline void hrtick_rq_init(struct rq *rq)
  303. {
  304. }
  305. #endif /* CONFIG_SCHED_HRTICK */
  306. /*
  307. * cmpxchg based fetch_or, macro so it works for different integer types
  308. */
  309. #define fetch_or(ptr, mask) \
  310. ({ \
  311. typeof(ptr) _ptr = (ptr); \
  312. typeof(mask) _mask = (mask); \
  313. typeof(*_ptr) _old, _val = *_ptr; \
  314. \
  315. for (;;) { \
  316. _old = cmpxchg(_ptr, _val, _val | _mask); \
  317. if (_old == _val) \
  318. break; \
  319. _val = _old; \
  320. } \
  321. _old; \
  322. })
  323. #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
  324. /*
  325. * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
  326. * this avoids any races wrt polling state changes and thereby avoids
  327. * spurious IPIs.
  328. */
  329. static bool set_nr_and_not_polling(struct task_struct *p)
  330. {
  331. struct thread_info *ti = task_thread_info(p);
  332. return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
  333. }
  334. /*
  335. * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
  336. *
  337. * If this returns true, then the idle task promises to call
  338. * sched_ttwu_pending() and reschedule soon.
  339. */
  340. static bool set_nr_if_polling(struct task_struct *p)
  341. {
  342. struct thread_info *ti = task_thread_info(p);
  343. typeof(ti->flags) old, val = READ_ONCE(ti->flags);
  344. for (;;) {
  345. if (!(val & _TIF_POLLING_NRFLAG))
  346. return false;
  347. if (val & _TIF_NEED_RESCHED)
  348. return true;
  349. old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
  350. if (old == val)
  351. break;
  352. val = old;
  353. }
  354. return true;
  355. }
  356. #else
  357. static bool set_nr_and_not_polling(struct task_struct *p)
  358. {
  359. set_tsk_need_resched(p);
  360. return true;
  361. }
  362. #ifdef CONFIG_SMP
  363. static bool set_nr_if_polling(struct task_struct *p)
  364. {
  365. return false;
  366. }
  367. #endif
  368. #endif
  369. void wake_q_add(struct wake_q_head *head, struct task_struct *task)
  370. {
  371. struct wake_q_node *node = &task->wake_q;
  372. /*
  373. * Atomically grab the task, if ->wake_q is !nil already it means
  374. * its already queued (either by us or someone else) and will get the
  375. * wakeup due to that.
  376. *
  377. * This cmpxchg() implies a full barrier, which pairs with the write
  378. * barrier implied by the wakeup in wake_up_q().
  379. */
  380. if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
  381. return;
  382. get_task_struct(task);
  383. /*
  384. * The head is context local, there can be no concurrency.
  385. */
  386. *head->lastp = node;
  387. head->lastp = &node->next;
  388. }
  389. void wake_up_q(struct wake_q_head *head)
  390. {
  391. struct wake_q_node *node = head->first;
  392. while (node != WAKE_Q_TAIL) {
  393. struct task_struct *task;
  394. task = container_of(node, struct task_struct, wake_q);
  395. BUG_ON(!task);
  396. /* Task can safely be re-inserted now: */
  397. node = node->next;
  398. task->wake_q.next = NULL;
  399. /*
  400. * wake_up_process() implies a wmb() to pair with the queueing
  401. * in wake_q_add() so as not to miss wakeups.
  402. */
  403. wake_up_process(task);
  404. put_task_struct(task);
  405. }
  406. }
  407. /*
  408. * resched_curr - mark rq's current task 'to be rescheduled now'.
  409. *
  410. * On UP this means the setting of the need_resched flag, on SMP it
  411. * might also involve a cross-CPU call to trigger the scheduler on
  412. * the target CPU.
  413. */
  414. void resched_curr(struct rq *rq)
  415. {
  416. struct task_struct *curr = rq->curr;
  417. int cpu;
  418. lockdep_assert_held(&rq->lock);
  419. if (test_tsk_need_resched(curr))
  420. return;
  421. cpu = cpu_of(rq);
  422. if (cpu == smp_processor_id()) {
  423. set_tsk_need_resched(curr);
  424. set_preempt_need_resched();
  425. return;
  426. }
  427. if (set_nr_and_not_polling(curr))
  428. smp_send_reschedule(cpu);
  429. else
  430. trace_sched_wake_idle_without_ipi(cpu);
  431. }
  432. void resched_cpu(int cpu)
  433. {
  434. struct rq *rq = cpu_rq(cpu);
  435. unsigned long flags;
  436. raw_spin_lock_irqsave(&rq->lock, flags);
  437. if (cpu_online(cpu) || cpu == smp_processor_id())
  438. resched_curr(rq);
  439. raw_spin_unlock_irqrestore(&rq->lock, flags);
  440. }
  441. #ifdef CONFIG_SMP
  442. #ifdef CONFIG_NO_HZ_COMMON
  443. /*
  444. * In the semi idle case, use the nearest busy CPU for migrating timers
  445. * from an idle CPU. This is good for power-savings.
  446. *
  447. * We don't do similar optimization for completely idle system, as
  448. * selecting an idle CPU will add more delays to the timers than intended
  449. * (as that CPU's timer base may not be uptodate wrt jiffies etc).
  450. */
  451. int get_nohz_timer_target(void)
  452. {
  453. int i, cpu = smp_processor_id();
  454. struct sched_domain *sd;
  455. if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
  456. return cpu;
  457. rcu_read_lock();
  458. for_each_domain(cpu, sd) {
  459. for_each_cpu(i, sched_domain_span(sd)) {
  460. if (cpu == i)
  461. continue;
  462. if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
  463. cpu = i;
  464. goto unlock;
  465. }
  466. }
  467. }
  468. if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
  469. cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
  470. unlock:
  471. rcu_read_unlock();
  472. return cpu;
  473. }
  474. /*
  475. * When add_timer_on() enqueues a timer into the timer wheel of an
  476. * idle CPU then this timer might expire before the next timer event
  477. * which is scheduled to wake up that CPU. In case of a completely
  478. * idle system the next event might even be infinite time into the
  479. * future. wake_up_idle_cpu() ensures that the CPU is woken up and
  480. * leaves the inner idle loop so the newly added timer is taken into
  481. * account when the CPU goes back to idle and evaluates the timer
  482. * wheel for the next timer event.
  483. */
  484. static void wake_up_idle_cpu(int cpu)
  485. {
  486. struct rq *rq = cpu_rq(cpu);
  487. if (cpu == smp_processor_id())
  488. return;
  489. if (set_nr_and_not_polling(rq->idle))
  490. smp_send_reschedule(cpu);
  491. else
  492. trace_sched_wake_idle_without_ipi(cpu);
  493. }
  494. static bool wake_up_full_nohz_cpu(int cpu)
  495. {
  496. /*
  497. * We just need the target to call irq_exit() and re-evaluate
  498. * the next tick. The nohz full kick at least implies that.
  499. * If needed we can still optimize that later with an
  500. * empty IRQ.
  501. */
  502. if (cpu_is_offline(cpu))
  503. return true; /* Don't try to wake offline CPUs. */
  504. if (tick_nohz_full_cpu(cpu)) {
  505. if (cpu != smp_processor_id() ||
  506. tick_nohz_tick_stopped())
  507. tick_nohz_full_kick_cpu(cpu);
  508. return true;
  509. }
  510. return false;
  511. }
  512. /*
  513. * Wake up the specified CPU. If the CPU is going offline, it is the
  514. * caller's responsibility to deal with the lost wakeup, for example,
  515. * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
  516. */
  517. void wake_up_nohz_cpu(int cpu)
  518. {
  519. if (!wake_up_full_nohz_cpu(cpu))
  520. wake_up_idle_cpu(cpu);
  521. }
  522. static inline bool got_nohz_idle_kick(void)
  523. {
  524. int cpu = smp_processor_id();
  525. if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)))
  526. return false;
  527. if (idle_cpu(cpu) && !need_resched())
  528. return true;
  529. /*
  530. * We can't run Idle Load Balance on this CPU for this time so we
  531. * cancel it and clear NOHZ_BALANCE_KICK
  532. */
  533. clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu));
  534. return false;
  535. }
  536. #else /* CONFIG_NO_HZ_COMMON */
  537. static inline bool got_nohz_idle_kick(void)
  538. {
  539. return false;
  540. }
  541. #endif /* CONFIG_NO_HZ_COMMON */
  542. #ifdef CONFIG_NO_HZ_FULL
  543. bool sched_can_stop_tick(struct rq *rq)
  544. {
  545. int fifo_nr_running;
  546. /* Deadline tasks, even if single, need the tick */
  547. if (rq->dl.dl_nr_running)
  548. return false;
  549. /*
  550. * If there are more than one RR tasks, we need the tick to effect the
  551. * actual RR behaviour.
  552. */
  553. if (rq->rt.rr_nr_running) {
  554. if (rq->rt.rr_nr_running == 1)
  555. return true;
  556. else
  557. return false;
  558. }
  559. /*
  560. * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
  561. * forced preemption between FIFO tasks.
  562. */
  563. fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
  564. if (fifo_nr_running)
  565. return true;
  566. /*
  567. * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
  568. * if there's more than one we need the tick for involuntary
  569. * preemption.
  570. */
  571. if (rq->nr_running > 1)
  572. return false;
  573. return true;
  574. }
  575. #endif /* CONFIG_NO_HZ_FULL */
  576. void sched_avg_update(struct rq *rq)
  577. {
  578. s64 period = sched_avg_period();
  579. while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
  580. /*
  581. * Inline assembly required to prevent the compiler
  582. * optimising this loop into a divmod call.
  583. * See __iter_div_u64_rem() for another example of this.
  584. */
  585. asm("" : "+rm" (rq->age_stamp));
  586. rq->age_stamp += period;
  587. rq->rt_avg /= 2;
  588. }
  589. }
  590. #endif /* CONFIG_SMP */
  591. #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
  592. (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
  593. /*
  594. * Iterate task_group tree rooted at *from, calling @down when first entering a
  595. * node and @up when leaving it for the final time.
  596. *
  597. * Caller must hold rcu_lock or sufficient equivalent.
  598. */
  599. int walk_tg_tree_from(struct task_group *from,
  600. tg_visitor down, tg_visitor up, void *data)
  601. {
  602. struct task_group *parent, *child;
  603. int ret;
  604. parent = from;
  605. down:
  606. ret = (*down)(parent, data);
  607. if (ret)
  608. goto out;
  609. list_for_each_entry_rcu(child, &parent->children, siblings) {
  610. parent = child;
  611. goto down;
  612. up:
  613. continue;
  614. }
  615. ret = (*up)(parent, data);
  616. if (ret || parent == from)
  617. goto out;
  618. child = parent;
  619. parent = parent->parent;
  620. if (parent)
  621. goto up;
  622. out:
  623. return ret;
  624. }
  625. int tg_nop(struct task_group *tg, void *data)
  626. {
  627. return 0;
  628. }
  629. #endif
  630. static void set_load_weight(struct task_struct *p, bool update_load)
  631. {
  632. int prio = p->static_prio - MAX_RT_PRIO;
  633. struct load_weight *load = &p->se.load;
  634. /*
  635. * SCHED_IDLE tasks get minimal weight:
  636. */
  637. if (idle_policy(p->policy)) {
  638. load->weight = scale_load(WEIGHT_IDLEPRIO);
  639. load->inv_weight = WMULT_IDLEPRIO;
  640. return;
  641. }
  642. /*
  643. * SCHED_OTHER tasks have to update their load when changing their
  644. * weight
  645. */
  646. if (update_load && p->sched_class == &fair_sched_class) {
  647. reweight_task(p, prio);
  648. } else {
  649. load->weight = scale_load(sched_prio_to_weight[prio]);
  650. load->inv_weight = sched_prio_to_wmult[prio];
  651. }
  652. }
  653. static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
  654. {
  655. if (!(flags & ENQUEUE_NOCLOCK))
  656. update_rq_clock(rq);
  657. if (!(flags & ENQUEUE_RESTORE))
  658. sched_info_queued(rq, p);
  659. p->sched_class->enqueue_task(rq, p, flags);
  660. }
  661. static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
  662. {
  663. if (!(flags & DEQUEUE_NOCLOCK))
  664. update_rq_clock(rq);
  665. if (!(flags & DEQUEUE_SAVE))
  666. sched_info_dequeued(rq, p);
  667. p->sched_class->dequeue_task(rq, p, flags);
  668. }
  669. void activate_task(struct rq *rq, struct task_struct *p, int flags)
  670. {
  671. if (task_contributes_to_load(p))
  672. rq->nr_uninterruptible--;
  673. enqueue_task(rq, p, flags);
  674. }
  675. void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
  676. {
  677. if (task_contributes_to_load(p))
  678. rq->nr_uninterruptible++;
  679. dequeue_task(rq, p, flags);
  680. }
  681. /*
  682. * __normal_prio - return the priority that is based on the static prio
  683. */
  684. static inline int __normal_prio(struct task_struct *p)
  685. {
  686. return p->static_prio;
  687. }
  688. /*
  689. * Calculate the expected normal priority: i.e. priority
  690. * without taking RT-inheritance into account. Might be
  691. * boosted by interactivity modifiers. Changes upon fork,
  692. * setprio syscalls, and whenever the interactivity
  693. * estimator recalculates.
  694. */
  695. static inline int normal_prio(struct task_struct *p)
  696. {
  697. int prio;
  698. if (task_has_dl_policy(p))
  699. prio = MAX_DL_PRIO-1;
  700. else if (task_has_rt_policy(p))
  701. prio = MAX_RT_PRIO-1 - p->rt_priority;
  702. else
  703. prio = __normal_prio(p);
  704. return prio;
  705. }
  706. /*
  707. * Calculate the current priority, i.e. the priority
  708. * taken into account by the scheduler. This value might
  709. * be boosted by RT tasks, or might be boosted by
  710. * interactivity modifiers. Will be RT if the task got
  711. * RT-boosted. If not then it returns p->normal_prio.
  712. */
  713. static int effective_prio(struct task_struct *p)
  714. {
  715. p->normal_prio = normal_prio(p);
  716. /*
  717. * If we are RT tasks or we were boosted to RT priority,
  718. * keep the priority unchanged. Otherwise, update priority
  719. * to the normal priority:
  720. */
  721. if (!rt_prio(p->prio))
  722. return p->normal_prio;
  723. return p->prio;
  724. }
  725. /**
  726. * task_curr - is this task currently executing on a CPU?
  727. * @p: the task in question.
  728. *
  729. * Return: 1 if the task is currently executing. 0 otherwise.
  730. */
  731. inline int task_curr(const struct task_struct *p)
  732. {
  733. return cpu_curr(task_cpu(p)) == p;
  734. }
  735. /*
  736. * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
  737. * use the balance_callback list if you want balancing.
  738. *
  739. * this means any call to check_class_changed() must be followed by a call to
  740. * balance_callback().
  741. */
  742. static inline void check_class_changed(struct rq *rq, struct task_struct *p,
  743. const struct sched_class *prev_class,
  744. int oldprio)
  745. {
  746. if (prev_class != p->sched_class) {
  747. if (prev_class->switched_from)
  748. prev_class->switched_from(rq, p);
  749. p->sched_class->switched_to(rq, p);
  750. } else if (oldprio != p->prio || dl_task(p))
  751. p->sched_class->prio_changed(rq, p, oldprio);
  752. }
  753. void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
  754. {
  755. const struct sched_class *class;
  756. if (p->sched_class == rq->curr->sched_class) {
  757. rq->curr->sched_class->check_preempt_curr(rq, p, flags);
  758. } else {
  759. for_each_class(class) {
  760. if (class == rq->curr->sched_class)
  761. break;
  762. if (class == p->sched_class) {
  763. resched_curr(rq);
  764. break;
  765. }
  766. }
  767. }
  768. /*
  769. * A queue event has occurred, and we're going to schedule. In
  770. * this case, we can save a useless back to back clock update.
  771. */
  772. if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
  773. rq_clock_skip_update(rq, true);
  774. }
  775. #ifdef CONFIG_SMP
  776. /*
  777. * This is how migration works:
  778. *
  779. * 1) we invoke migration_cpu_stop() on the target CPU using
  780. * stop_one_cpu().
  781. * 2) stopper starts to run (implicitly forcing the migrated thread
  782. * off the CPU)
  783. * 3) it checks whether the migrated task is still in the wrong runqueue.
  784. * 4) if it's in the wrong runqueue then the migration thread removes
  785. * it and puts it into the right queue.
  786. * 5) stopper completes and stop_one_cpu() returns and the migration
  787. * is done.
  788. */
  789. /*
  790. * move_queued_task - move a queued task to new rq.
  791. *
  792. * Returns (locked) new rq. Old rq's lock is released.
  793. */
  794. static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
  795. struct task_struct *p, int new_cpu)
  796. {
  797. lockdep_assert_held(&rq->lock);
  798. p->on_rq = TASK_ON_RQ_MIGRATING;
  799. dequeue_task(rq, p, DEQUEUE_NOCLOCK);
  800. set_task_cpu(p, new_cpu);
  801. rq_unlock(rq, rf);
  802. rq = cpu_rq(new_cpu);
  803. rq_lock(rq, rf);
  804. BUG_ON(task_cpu(p) != new_cpu);
  805. enqueue_task(rq, p, 0);
  806. p->on_rq = TASK_ON_RQ_QUEUED;
  807. check_preempt_curr(rq, p, 0);
  808. return rq;
  809. }
  810. struct migration_arg {
  811. struct task_struct *task;
  812. int dest_cpu;
  813. };
  814. /*
  815. * Move (not current) task off this CPU, onto the destination CPU. We're doing
  816. * this because either it can't run here any more (set_cpus_allowed()
  817. * away from this CPU, or CPU going down), or because we're
  818. * attempting to rebalance this task on exec (sched_exec).
  819. *
  820. * So we race with normal scheduler movements, but that's OK, as long
  821. * as the task is no longer on this CPU.
  822. */
  823. static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
  824. struct task_struct *p, int dest_cpu)
  825. {
  826. if (p->flags & PF_KTHREAD) {
  827. if (unlikely(!cpu_online(dest_cpu)))
  828. return rq;
  829. } else {
  830. if (unlikely(!cpu_active(dest_cpu)))
  831. return rq;
  832. }
  833. /* Affinity changed (again). */
  834. if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
  835. return rq;
  836. update_rq_clock(rq);
  837. rq = move_queued_task(rq, rf, p, dest_cpu);
  838. return rq;
  839. }
  840. /*
  841. * migration_cpu_stop - this will be executed by a highprio stopper thread
  842. * and performs thread migration by bumping thread off CPU then
  843. * 'pushing' onto another runqueue.
  844. */
  845. static int migration_cpu_stop(void *data)
  846. {
  847. struct migration_arg *arg = data;
  848. struct task_struct *p = arg->task;
  849. struct rq *rq = this_rq();
  850. struct rq_flags rf;
  851. /*
  852. * The original target CPU might have gone down and we might
  853. * be on another CPU but it doesn't matter.
  854. */
  855. local_irq_disable();
  856. /*
  857. * We need to explicitly wake pending tasks before running
  858. * __migrate_task() such that we will not miss enforcing cpus_allowed
  859. * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
  860. */
  861. sched_ttwu_pending();
  862. raw_spin_lock(&p->pi_lock);
  863. rq_lock(rq, &rf);
  864. /*
  865. * If task_rq(p) != rq, it cannot be migrated here, because we're
  866. * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
  867. * we're holding p->pi_lock.
  868. */
  869. if (task_rq(p) == rq) {
  870. if (task_on_rq_queued(p))
  871. rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
  872. else
  873. p->wake_cpu = arg->dest_cpu;
  874. }
  875. rq_unlock(rq, &rf);
  876. raw_spin_unlock(&p->pi_lock);
  877. local_irq_enable();
  878. return 0;
  879. }
  880. /*
  881. * sched_class::set_cpus_allowed must do the below, but is not required to
  882. * actually call this function.
  883. */
  884. void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
  885. {
  886. cpumask_copy(&p->cpus_allowed, new_mask);
  887. p->nr_cpus_allowed = cpumask_weight(new_mask);
  888. }
  889. void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
  890. {
  891. struct rq *rq = task_rq(p);
  892. bool queued, running;
  893. lockdep_assert_held(&p->pi_lock);
  894. queued = task_on_rq_queued(p);
  895. running = task_current(rq, p);
  896. if (queued) {
  897. /*
  898. * Because __kthread_bind() calls this on blocked tasks without
  899. * holding rq->lock.
  900. */
  901. lockdep_assert_held(&rq->lock);
  902. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  903. }
  904. if (running)
  905. put_prev_task(rq, p);
  906. p->sched_class->set_cpus_allowed(p, new_mask);
  907. if (queued)
  908. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  909. if (running)
  910. set_curr_task(rq, p);
  911. }
  912. /*
  913. * Change a given task's CPU affinity. Migrate the thread to a
  914. * proper CPU and schedule it away if the CPU it's executing on
  915. * is removed from the allowed bitmask.
  916. *
  917. * NOTE: the caller must have a valid reference to the task, the
  918. * task must not exit() & deallocate itself prematurely. The
  919. * call is not atomic; no spinlocks may be held.
  920. */
  921. static int __set_cpus_allowed_ptr(struct task_struct *p,
  922. const struct cpumask *new_mask, bool check)
  923. {
  924. const struct cpumask *cpu_valid_mask = cpu_active_mask;
  925. unsigned int dest_cpu;
  926. struct rq_flags rf;
  927. struct rq *rq;
  928. int ret = 0;
  929. rq = task_rq_lock(p, &rf);
  930. update_rq_clock(rq);
  931. if (p->flags & PF_KTHREAD) {
  932. /*
  933. * Kernel threads are allowed on online && !active CPUs
  934. */
  935. cpu_valid_mask = cpu_online_mask;
  936. }
  937. /*
  938. * Must re-check here, to close a race against __kthread_bind(),
  939. * sched_setaffinity() is not guaranteed to observe the flag.
  940. */
  941. if (check && (p->flags & PF_NO_SETAFFINITY)) {
  942. ret = -EINVAL;
  943. goto out;
  944. }
  945. if (cpumask_equal(&p->cpus_allowed, new_mask))
  946. goto out;
  947. if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
  948. ret = -EINVAL;
  949. goto out;
  950. }
  951. do_set_cpus_allowed(p, new_mask);
  952. if (p->flags & PF_KTHREAD) {
  953. /*
  954. * For kernel threads that do indeed end up on online &&
  955. * !active we want to ensure they are strict per-CPU threads.
  956. */
  957. WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
  958. !cpumask_intersects(new_mask, cpu_active_mask) &&
  959. p->nr_cpus_allowed != 1);
  960. }
  961. /* Can the task run on the task's current CPU? If so, we're done */
  962. if (cpumask_test_cpu(task_cpu(p), new_mask))
  963. goto out;
  964. dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
  965. if (task_running(rq, p) || p->state == TASK_WAKING) {
  966. struct migration_arg arg = { p, dest_cpu };
  967. /* Need help from migration thread: drop lock and wait. */
  968. task_rq_unlock(rq, p, &rf);
  969. stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
  970. tlb_migrate_finish(p->mm);
  971. return 0;
  972. } else if (task_on_rq_queued(p)) {
  973. /*
  974. * OK, since we're going to drop the lock immediately
  975. * afterwards anyway.
  976. */
  977. rq = move_queued_task(rq, &rf, p, dest_cpu);
  978. }
  979. out:
  980. task_rq_unlock(rq, p, &rf);
  981. return ret;
  982. }
  983. int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
  984. {
  985. return __set_cpus_allowed_ptr(p, new_mask, false);
  986. }
  987. EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
  988. void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
  989. {
  990. #ifdef CONFIG_SCHED_DEBUG
  991. /*
  992. * We should never call set_task_cpu() on a blocked task,
  993. * ttwu() will sort out the placement.
  994. */
  995. WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
  996. !p->on_rq);
  997. /*
  998. * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
  999. * because schedstat_wait_{start,end} rebase migrating task's wait_start
  1000. * time relying on p->on_rq.
  1001. */
  1002. WARN_ON_ONCE(p->state == TASK_RUNNING &&
  1003. p->sched_class == &fair_sched_class &&
  1004. (p->on_rq && !task_on_rq_migrating(p)));
  1005. #ifdef CONFIG_LOCKDEP
  1006. /*
  1007. * The caller should hold either p->pi_lock or rq->lock, when changing
  1008. * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
  1009. *
  1010. * sched_move_task() holds both and thus holding either pins the cgroup,
  1011. * see task_group().
  1012. *
  1013. * Furthermore, all task_rq users should acquire both locks, see
  1014. * task_rq_lock().
  1015. */
  1016. WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
  1017. lockdep_is_held(&task_rq(p)->lock)));
  1018. #endif
  1019. /*
  1020. * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
  1021. */
  1022. WARN_ON_ONCE(!cpu_online(new_cpu));
  1023. #endif
  1024. trace_sched_migrate_task(p, new_cpu);
  1025. if (task_cpu(p) != new_cpu) {
  1026. if (p->sched_class->migrate_task_rq)
  1027. p->sched_class->migrate_task_rq(p);
  1028. p->se.nr_migrations++;
  1029. perf_event_task_migrate(p);
  1030. }
  1031. __set_task_cpu(p, new_cpu);
  1032. }
  1033. static void __migrate_swap_task(struct task_struct *p, int cpu)
  1034. {
  1035. if (task_on_rq_queued(p)) {
  1036. struct rq *src_rq, *dst_rq;
  1037. struct rq_flags srf, drf;
  1038. src_rq = task_rq(p);
  1039. dst_rq = cpu_rq(cpu);
  1040. rq_pin_lock(src_rq, &srf);
  1041. rq_pin_lock(dst_rq, &drf);
  1042. p->on_rq = TASK_ON_RQ_MIGRATING;
  1043. deactivate_task(src_rq, p, 0);
  1044. set_task_cpu(p, cpu);
  1045. activate_task(dst_rq, p, 0);
  1046. p->on_rq = TASK_ON_RQ_QUEUED;
  1047. check_preempt_curr(dst_rq, p, 0);
  1048. rq_unpin_lock(dst_rq, &drf);
  1049. rq_unpin_lock(src_rq, &srf);
  1050. } else {
  1051. /*
  1052. * Task isn't running anymore; make it appear like we migrated
  1053. * it before it went to sleep. This means on wakeup we make the
  1054. * previous CPU our target instead of where it really is.
  1055. */
  1056. p->wake_cpu = cpu;
  1057. }
  1058. }
  1059. struct migration_swap_arg {
  1060. struct task_struct *src_task, *dst_task;
  1061. int src_cpu, dst_cpu;
  1062. };
  1063. static int migrate_swap_stop(void *data)
  1064. {
  1065. struct migration_swap_arg *arg = data;
  1066. struct rq *src_rq, *dst_rq;
  1067. int ret = -EAGAIN;
  1068. if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
  1069. return -EAGAIN;
  1070. src_rq = cpu_rq(arg->src_cpu);
  1071. dst_rq = cpu_rq(arg->dst_cpu);
  1072. double_raw_lock(&arg->src_task->pi_lock,
  1073. &arg->dst_task->pi_lock);
  1074. double_rq_lock(src_rq, dst_rq);
  1075. if (task_cpu(arg->dst_task) != arg->dst_cpu)
  1076. goto unlock;
  1077. if (task_cpu(arg->src_task) != arg->src_cpu)
  1078. goto unlock;
  1079. if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
  1080. goto unlock;
  1081. if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
  1082. goto unlock;
  1083. __migrate_swap_task(arg->src_task, arg->dst_cpu);
  1084. __migrate_swap_task(arg->dst_task, arg->src_cpu);
  1085. ret = 0;
  1086. unlock:
  1087. double_rq_unlock(src_rq, dst_rq);
  1088. raw_spin_unlock(&arg->dst_task->pi_lock);
  1089. raw_spin_unlock(&arg->src_task->pi_lock);
  1090. return ret;
  1091. }
  1092. /*
  1093. * Cross migrate two tasks
  1094. */
  1095. int migrate_swap(struct task_struct *cur, struct task_struct *p)
  1096. {
  1097. struct migration_swap_arg arg;
  1098. int ret = -EINVAL;
  1099. arg = (struct migration_swap_arg){
  1100. .src_task = cur,
  1101. .src_cpu = task_cpu(cur),
  1102. .dst_task = p,
  1103. .dst_cpu = task_cpu(p),
  1104. };
  1105. if (arg.src_cpu == arg.dst_cpu)
  1106. goto out;
  1107. /*
  1108. * These three tests are all lockless; this is OK since all of them
  1109. * will be re-checked with proper locks held further down the line.
  1110. */
  1111. if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
  1112. goto out;
  1113. if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
  1114. goto out;
  1115. if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
  1116. goto out;
  1117. trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
  1118. ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
  1119. out:
  1120. return ret;
  1121. }
  1122. /*
  1123. * wait_task_inactive - wait for a thread to unschedule.
  1124. *
  1125. * If @match_state is nonzero, it's the @p->state value just checked and
  1126. * not expected to change. If it changes, i.e. @p might have woken up,
  1127. * then return zero. When we succeed in waiting for @p to be off its CPU,
  1128. * we return a positive number (its total switch count). If a second call
  1129. * a short while later returns the same number, the caller can be sure that
  1130. * @p has remained unscheduled the whole time.
  1131. *
  1132. * The caller must ensure that the task *will* unschedule sometime soon,
  1133. * else this function might spin for a *long* time. This function can't
  1134. * be called with interrupts off, or it may introduce deadlock with
  1135. * smp_call_function() if an IPI is sent by the same process we are
  1136. * waiting to become inactive.
  1137. */
  1138. unsigned long wait_task_inactive(struct task_struct *p, long match_state)
  1139. {
  1140. int running, queued;
  1141. struct rq_flags rf;
  1142. unsigned long ncsw;
  1143. struct rq *rq;
  1144. for (;;) {
  1145. /*
  1146. * We do the initial early heuristics without holding
  1147. * any task-queue locks at all. We'll only try to get
  1148. * the runqueue lock when things look like they will
  1149. * work out!
  1150. */
  1151. rq = task_rq(p);
  1152. /*
  1153. * If the task is actively running on another CPU
  1154. * still, just relax and busy-wait without holding
  1155. * any locks.
  1156. *
  1157. * NOTE! Since we don't hold any locks, it's not
  1158. * even sure that "rq" stays as the right runqueue!
  1159. * But we don't care, since "task_running()" will
  1160. * return false if the runqueue has changed and p
  1161. * is actually now running somewhere else!
  1162. */
  1163. while (task_running(rq, p)) {
  1164. if (match_state && unlikely(p->state != match_state))
  1165. return 0;
  1166. cpu_relax();
  1167. }
  1168. /*
  1169. * Ok, time to look more closely! We need the rq
  1170. * lock now, to be *sure*. If we're wrong, we'll
  1171. * just go back and repeat.
  1172. */
  1173. rq = task_rq_lock(p, &rf);
  1174. trace_sched_wait_task(p);
  1175. running = task_running(rq, p);
  1176. queued = task_on_rq_queued(p);
  1177. ncsw = 0;
  1178. if (!match_state || p->state == match_state)
  1179. ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
  1180. task_rq_unlock(rq, p, &rf);
  1181. /*
  1182. * If it changed from the expected state, bail out now.
  1183. */
  1184. if (unlikely(!ncsw))
  1185. break;
  1186. /*
  1187. * Was it really running after all now that we
  1188. * checked with the proper locks actually held?
  1189. *
  1190. * Oops. Go back and try again..
  1191. */
  1192. if (unlikely(running)) {
  1193. cpu_relax();
  1194. continue;
  1195. }
  1196. /*
  1197. * It's not enough that it's not actively running,
  1198. * it must be off the runqueue _entirely_, and not
  1199. * preempted!
  1200. *
  1201. * So if it was still runnable (but just not actively
  1202. * running right now), it's preempted, and we should
  1203. * yield - it could be a while.
  1204. */
  1205. if (unlikely(queued)) {
  1206. ktime_t to = NSEC_PER_SEC / HZ;
  1207. set_current_state(TASK_UNINTERRUPTIBLE);
  1208. schedule_hrtimeout(&to, HRTIMER_MODE_REL);
  1209. continue;
  1210. }
  1211. /*
  1212. * Ahh, all good. It wasn't running, and it wasn't
  1213. * runnable, which means that it will never become
  1214. * running in the future either. We're all done!
  1215. */
  1216. break;
  1217. }
  1218. return ncsw;
  1219. }
  1220. /***
  1221. * kick_process - kick a running thread to enter/exit the kernel
  1222. * @p: the to-be-kicked thread
  1223. *
  1224. * Cause a process which is running on another CPU to enter
  1225. * kernel-mode, without any delay. (to get signals handled.)
  1226. *
  1227. * NOTE: this function doesn't have to take the runqueue lock,
  1228. * because all it wants to ensure is that the remote task enters
  1229. * the kernel. If the IPI races and the task has been migrated
  1230. * to another CPU then no harm is done and the purpose has been
  1231. * achieved as well.
  1232. */
  1233. void kick_process(struct task_struct *p)
  1234. {
  1235. int cpu;
  1236. preempt_disable();
  1237. cpu = task_cpu(p);
  1238. if ((cpu != smp_processor_id()) && task_curr(p))
  1239. smp_send_reschedule(cpu);
  1240. preempt_enable();
  1241. }
  1242. EXPORT_SYMBOL_GPL(kick_process);
  1243. /*
  1244. * ->cpus_allowed is protected by both rq->lock and p->pi_lock
  1245. *
  1246. * A few notes on cpu_active vs cpu_online:
  1247. *
  1248. * - cpu_active must be a subset of cpu_online
  1249. *
  1250. * - on cpu-up we allow per-cpu kthreads on the online && !active cpu,
  1251. * see __set_cpus_allowed_ptr(). At this point the newly online
  1252. * CPU isn't yet part of the sched domains, and balancing will not
  1253. * see it.
  1254. *
  1255. * - on CPU-down we clear cpu_active() to mask the sched domains and
  1256. * avoid the load balancer to place new tasks on the to be removed
  1257. * CPU. Existing tasks will remain running there and will be taken
  1258. * off.
  1259. *
  1260. * This means that fallback selection must not select !active CPUs.
  1261. * And can assume that any active CPU must be online. Conversely
  1262. * select_task_rq() below may allow selection of !active CPUs in order
  1263. * to satisfy the above rules.
  1264. */
  1265. static int select_fallback_rq(int cpu, struct task_struct *p)
  1266. {
  1267. int nid = cpu_to_node(cpu);
  1268. const struct cpumask *nodemask = NULL;
  1269. enum { cpuset, possible, fail } state = cpuset;
  1270. int dest_cpu;
  1271. /*
  1272. * If the node that the CPU is on has been offlined, cpu_to_node()
  1273. * will return -1. There is no CPU on the node, and we should
  1274. * select the CPU on the other node.
  1275. */
  1276. if (nid != -1) {
  1277. nodemask = cpumask_of_node(nid);
  1278. /* Look for allowed, online CPU in same node. */
  1279. for_each_cpu(dest_cpu, nodemask) {
  1280. if (!cpu_active(dest_cpu))
  1281. continue;
  1282. if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
  1283. return dest_cpu;
  1284. }
  1285. }
  1286. for (;;) {
  1287. /* Any allowed, online CPU? */
  1288. for_each_cpu(dest_cpu, &p->cpus_allowed) {
  1289. if (!(p->flags & PF_KTHREAD) && !cpu_active(dest_cpu))
  1290. continue;
  1291. if (!cpu_online(dest_cpu))
  1292. continue;
  1293. goto out;
  1294. }
  1295. /* No more Mr. Nice Guy. */
  1296. switch (state) {
  1297. case cpuset:
  1298. if (IS_ENABLED(CONFIG_CPUSETS)) {
  1299. cpuset_cpus_allowed_fallback(p);
  1300. state = possible;
  1301. break;
  1302. }
  1303. /* Fall-through */
  1304. case possible:
  1305. do_set_cpus_allowed(p, cpu_possible_mask);
  1306. state = fail;
  1307. break;
  1308. case fail:
  1309. BUG();
  1310. break;
  1311. }
  1312. }
  1313. out:
  1314. if (state != cpuset) {
  1315. /*
  1316. * Don't tell them about moving exiting tasks or
  1317. * kernel threads (both mm NULL), since they never
  1318. * leave kernel.
  1319. */
  1320. if (p->mm && printk_ratelimit()) {
  1321. printk_deferred("process %d (%s) no longer affine to cpu%d\n",
  1322. task_pid_nr(p), p->comm, cpu);
  1323. }
  1324. }
  1325. return dest_cpu;
  1326. }
  1327. /*
  1328. * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
  1329. */
  1330. static inline
  1331. int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
  1332. {
  1333. lockdep_assert_held(&p->pi_lock);
  1334. if (p->nr_cpus_allowed > 1)
  1335. cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
  1336. else
  1337. cpu = cpumask_any(&p->cpus_allowed);
  1338. /*
  1339. * In order not to call set_task_cpu() on a blocking task we need
  1340. * to rely on ttwu() to place the task on a valid ->cpus_allowed
  1341. * CPU.
  1342. *
  1343. * Since this is common to all placement strategies, this lives here.
  1344. *
  1345. * [ this allows ->select_task() to simply return task_cpu(p) and
  1346. * not worry about this generic constraint ]
  1347. */
  1348. if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
  1349. !cpu_online(cpu)))
  1350. cpu = select_fallback_rq(task_cpu(p), p);
  1351. return cpu;
  1352. }
  1353. static void update_avg(u64 *avg, u64 sample)
  1354. {
  1355. s64 diff = sample - *avg;
  1356. *avg += diff >> 3;
  1357. }
  1358. void sched_set_stop_task(int cpu, struct task_struct *stop)
  1359. {
  1360. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  1361. struct task_struct *old_stop = cpu_rq(cpu)->stop;
  1362. if (stop) {
  1363. /*
  1364. * Make it appear like a SCHED_FIFO task, its something
  1365. * userspace knows about and won't get confused about.
  1366. *
  1367. * Also, it will make PI more or less work without too
  1368. * much confusion -- but then, stop work should not
  1369. * rely on PI working anyway.
  1370. */
  1371. sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
  1372. stop->sched_class = &stop_sched_class;
  1373. }
  1374. cpu_rq(cpu)->stop = stop;
  1375. if (old_stop) {
  1376. /*
  1377. * Reset it back to a normal scheduling class so that
  1378. * it can die in pieces.
  1379. */
  1380. old_stop->sched_class = &rt_sched_class;
  1381. }
  1382. }
  1383. #else
  1384. static inline int __set_cpus_allowed_ptr(struct task_struct *p,
  1385. const struct cpumask *new_mask, bool check)
  1386. {
  1387. return set_cpus_allowed_ptr(p, new_mask);
  1388. }
  1389. #endif /* CONFIG_SMP */
  1390. static void
  1391. ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
  1392. {
  1393. struct rq *rq;
  1394. if (!schedstat_enabled())
  1395. return;
  1396. rq = this_rq();
  1397. #ifdef CONFIG_SMP
  1398. if (cpu == rq->cpu) {
  1399. __schedstat_inc(rq->ttwu_local);
  1400. __schedstat_inc(p->se.statistics.nr_wakeups_local);
  1401. } else {
  1402. struct sched_domain *sd;
  1403. __schedstat_inc(p->se.statistics.nr_wakeups_remote);
  1404. rcu_read_lock();
  1405. for_each_domain(rq->cpu, sd) {
  1406. if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
  1407. __schedstat_inc(sd->ttwu_wake_remote);
  1408. break;
  1409. }
  1410. }
  1411. rcu_read_unlock();
  1412. }
  1413. if (wake_flags & WF_MIGRATED)
  1414. __schedstat_inc(p->se.statistics.nr_wakeups_migrate);
  1415. #endif /* CONFIG_SMP */
  1416. __schedstat_inc(rq->ttwu_count);
  1417. __schedstat_inc(p->se.statistics.nr_wakeups);
  1418. if (wake_flags & WF_SYNC)
  1419. __schedstat_inc(p->se.statistics.nr_wakeups_sync);
  1420. }
  1421. static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
  1422. {
  1423. activate_task(rq, p, en_flags);
  1424. p->on_rq = TASK_ON_RQ_QUEUED;
  1425. /* If a worker is waking up, notify the workqueue: */
  1426. if (p->flags & PF_WQ_WORKER)
  1427. wq_worker_waking_up(p, cpu_of(rq));
  1428. }
  1429. /*
  1430. * Mark the task runnable and perform wakeup-preemption.
  1431. */
  1432. static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
  1433. struct rq_flags *rf)
  1434. {
  1435. check_preempt_curr(rq, p, wake_flags);
  1436. p->state = TASK_RUNNING;
  1437. trace_sched_wakeup(p);
  1438. #ifdef CONFIG_SMP
  1439. if (p->sched_class->task_woken) {
  1440. /*
  1441. * Our task @p is fully woken up and running; so its safe to
  1442. * drop the rq->lock, hereafter rq is only used for statistics.
  1443. */
  1444. rq_unpin_lock(rq, rf);
  1445. p->sched_class->task_woken(rq, p);
  1446. rq_repin_lock(rq, rf);
  1447. }
  1448. if (rq->idle_stamp) {
  1449. u64 delta = rq_clock(rq) - rq->idle_stamp;
  1450. u64 max = 2*rq->max_idle_balance_cost;
  1451. update_avg(&rq->avg_idle, delta);
  1452. if (rq->avg_idle > max)
  1453. rq->avg_idle = max;
  1454. rq->idle_stamp = 0;
  1455. }
  1456. #endif
  1457. }
  1458. static void
  1459. ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
  1460. struct rq_flags *rf)
  1461. {
  1462. int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
  1463. lockdep_assert_held(&rq->lock);
  1464. #ifdef CONFIG_SMP
  1465. if (p->sched_contributes_to_load)
  1466. rq->nr_uninterruptible--;
  1467. if (wake_flags & WF_MIGRATED)
  1468. en_flags |= ENQUEUE_MIGRATED;
  1469. #endif
  1470. ttwu_activate(rq, p, en_flags);
  1471. ttwu_do_wakeup(rq, p, wake_flags, rf);
  1472. }
  1473. /*
  1474. * Called in case the task @p isn't fully descheduled from its runqueue,
  1475. * in this case we must do a remote wakeup. Its a 'light' wakeup though,
  1476. * since all we need to do is flip p->state to TASK_RUNNING, since
  1477. * the task is still ->on_rq.
  1478. */
  1479. static int ttwu_remote(struct task_struct *p, int wake_flags)
  1480. {
  1481. struct rq_flags rf;
  1482. struct rq *rq;
  1483. int ret = 0;
  1484. rq = __task_rq_lock(p, &rf);
  1485. if (task_on_rq_queued(p)) {
  1486. /* check_preempt_curr() may use rq clock */
  1487. update_rq_clock(rq);
  1488. ttwu_do_wakeup(rq, p, wake_flags, &rf);
  1489. ret = 1;
  1490. }
  1491. __task_rq_unlock(rq, &rf);
  1492. return ret;
  1493. }
  1494. #ifdef CONFIG_SMP
  1495. void sched_ttwu_pending(void)
  1496. {
  1497. struct rq *rq = this_rq();
  1498. struct llist_node *llist = llist_del_all(&rq->wake_list);
  1499. struct task_struct *p, *t;
  1500. struct rq_flags rf;
  1501. if (!llist)
  1502. return;
  1503. rq_lock_irqsave(rq, &rf);
  1504. update_rq_clock(rq);
  1505. llist_for_each_entry_safe(p, t, llist, wake_entry)
  1506. ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
  1507. rq_unlock_irqrestore(rq, &rf);
  1508. }
  1509. void scheduler_ipi(void)
  1510. {
  1511. /*
  1512. * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
  1513. * TIF_NEED_RESCHED remotely (for the first time) will also send
  1514. * this IPI.
  1515. */
  1516. preempt_fold_need_resched();
  1517. if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
  1518. return;
  1519. /*
  1520. * Not all reschedule IPI handlers call irq_enter/irq_exit, since
  1521. * traditionally all their work was done from the interrupt return
  1522. * path. Now that we actually do some work, we need to make sure
  1523. * we do call them.
  1524. *
  1525. * Some archs already do call them, luckily irq_enter/exit nest
  1526. * properly.
  1527. *
  1528. * Arguably we should visit all archs and update all handlers,
  1529. * however a fair share of IPIs are still resched only so this would
  1530. * somewhat pessimize the simple resched case.
  1531. */
  1532. irq_enter();
  1533. sched_ttwu_pending();
  1534. /*
  1535. * Check if someone kicked us for doing the nohz idle load balance.
  1536. */
  1537. if (unlikely(got_nohz_idle_kick())) {
  1538. this_rq()->idle_balance = 1;
  1539. raise_softirq_irqoff(SCHED_SOFTIRQ);
  1540. }
  1541. irq_exit();
  1542. }
  1543. static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
  1544. {
  1545. struct rq *rq = cpu_rq(cpu);
  1546. p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
  1547. if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
  1548. if (!set_nr_if_polling(rq->idle))
  1549. smp_send_reschedule(cpu);
  1550. else
  1551. trace_sched_wake_idle_without_ipi(cpu);
  1552. }
  1553. }
  1554. void wake_up_if_idle(int cpu)
  1555. {
  1556. struct rq *rq = cpu_rq(cpu);
  1557. struct rq_flags rf;
  1558. rcu_read_lock();
  1559. if (!is_idle_task(rcu_dereference(rq->curr)))
  1560. goto out;
  1561. if (set_nr_if_polling(rq->idle)) {
  1562. trace_sched_wake_idle_without_ipi(cpu);
  1563. } else {
  1564. rq_lock_irqsave(rq, &rf);
  1565. if (is_idle_task(rq->curr))
  1566. smp_send_reschedule(cpu);
  1567. /* Else CPU is not idle, do nothing here: */
  1568. rq_unlock_irqrestore(rq, &rf);
  1569. }
  1570. out:
  1571. rcu_read_unlock();
  1572. }
  1573. bool cpus_share_cache(int this_cpu, int that_cpu)
  1574. {
  1575. return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
  1576. }
  1577. #endif /* CONFIG_SMP */
  1578. static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
  1579. {
  1580. struct rq *rq = cpu_rq(cpu);
  1581. struct rq_flags rf;
  1582. #if defined(CONFIG_SMP)
  1583. if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
  1584. sched_clock_cpu(cpu); /* Sync clocks across CPUs */
  1585. ttwu_queue_remote(p, cpu, wake_flags);
  1586. return;
  1587. }
  1588. #endif
  1589. rq_lock(rq, &rf);
  1590. update_rq_clock(rq);
  1591. ttwu_do_activate(rq, p, wake_flags, &rf);
  1592. rq_unlock(rq, &rf);
  1593. }
  1594. /*
  1595. * Notes on Program-Order guarantees on SMP systems.
  1596. *
  1597. * MIGRATION
  1598. *
  1599. * The basic program-order guarantee on SMP systems is that when a task [t]
  1600. * migrates, all its activity on its old CPU [c0] happens-before any subsequent
  1601. * execution on its new CPU [c1].
  1602. *
  1603. * For migration (of runnable tasks) this is provided by the following means:
  1604. *
  1605. * A) UNLOCK of the rq(c0)->lock scheduling out task t
  1606. * B) migration for t is required to synchronize *both* rq(c0)->lock and
  1607. * rq(c1)->lock (if not at the same time, then in that order).
  1608. * C) LOCK of the rq(c1)->lock scheduling in task
  1609. *
  1610. * Transitivity guarantees that B happens after A and C after B.
  1611. * Note: we only require RCpc transitivity.
  1612. * Note: the CPU doing B need not be c0 or c1
  1613. *
  1614. * Example:
  1615. *
  1616. * CPU0 CPU1 CPU2
  1617. *
  1618. * LOCK rq(0)->lock
  1619. * sched-out X
  1620. * sched-in Y
  1621. * UNLOCK rq(0)->lock
  1622. *
  1623. * LOCK rq(0)->lock // orders against CPU0
  1624. * dequeue X
  1625. * UNLOCK rq(0)->lock
  1626. *
  1627. * LOCK rq(1)->lock
  1628. * enqueue X
  1629. * UNLOCK rq(1)->lock
  1630. *
  1631. * LOCK rq(1)->lock // orders against CPU2
  1632. * sched-out Z
  1633. * sched-in X
  1634. * UNLOCK rq(1)->lock
  1635. *
  1636. *
  1637. * BLOCKING -- aka. SLEEP + WAKEUP
  1638. *
  1639. * For blocking we (obviously) need to provide the same guarantee as for
  1640. * migration. However the means are completely different as there is no lock
  1641. * chain to provide order. Instead we do:
  1642. *
  1643. * 1) smp_store_release(X->on_cpu, 0)
  1644. * 2) smp_cond_load_acquire(!X->on_cpu)
  1645. *
  1646. * Example:
  1647. *
  1648. * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule)
  1649. *
  1650. * LOCK rq(0)->lock LOCK X->pi_lock
  1651. * dequeue X
  1652. * sched-out X
  1653. * smp_store_release(X->on_cpu, 0);
  1654. *
  1655. * smp_cond_load_acquire(&X->on_cpu, !VAL);
  1656. * X->state = WAKING
  1657. * set_task_cpu(X,2)
  1658. *
  1659. * LOCK rq(2)->lock
  1660. * enqueue X
  1661. * X->state = RUNNING
  1662. * UNLOCK rq(2)->lock
  1663. *
  1664. * LOCK rq(2)->lock // orders against CPU1
  1665. * sched-out Z
  1666. * sched-in X
  1667. * UNLOCK rq(2)->lock
  1668. *
  1669. * UNLOCK X->pi_lock
  1670. * UNLOCK rq(0)->lock
  1671. *
  1672. *
  1673. * However; for wakeups there is a second guarantee we must provide, namely we
  1674. * must observe the state that lead to our wakeup. That is, not only must our
  1675. * task observe its own prior state, it must also observe the stores prior to
  1676. * its wakeup.
  1677. *
  1678. * This means that any means of doing remote wakeups must order the CPU doing
  1679. * the wakeup against the CPU the task is going to end up running on. This,
  1680. * however, is already required for the regular Program-Order guarantee above,
  1681. * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
  1682. *
  1683. */
  1684. /**
  1685. * try_to_wake_up - wake up a thread
  1686. * @p: the thread to be awakened
  1687. * @state: the mask of task states that can be woken
  1688. * @wake_flags: wake modifier flags (WF_*)
  1689. *
  1690. * If (@state & @p->state) @p->state = TASK_RUNNING.
  1691. *
  1692. * If the task was not queued/runnable, also place it back on a runqueue.
  1693. *
  1694. * Atomic against schedule() which would dequeue a task, also see
  1695. * set_current_state().
  1696. *
  1697. * Return: %true if @p->state changes (an actual wakeup was done),
  1698. * %false otherwise.
  1699. */
  1700. static int
  1701. try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
  1702. {
  1703. unsigned long flags;
  1704. int cpu, success = 0;
  1705. /*
  1706. * If we are going to wake up a thread waiting for CONDITION we
  1707. * need to ensure that CONDITION=1 done by the caller can not be
  1708. * reordered with p->state check below. This pairs with mb() in
  1709. * set_current_state() the waiting thread does.
  1710. */
  1711. raw_spin_lock_irqsave(&p->pi_lock, flags);
  1712. smp_mb__after_spinlock();
  1713. if (!(p->state & state))
  1714. goto out;
  1715. trace_sched_waking(p);
  1716. /* We're going to change ->state: */
  1717. success = 1;
  1718. cpu = task_cpu(p);
  1719. /*
  1720. * Ensure we load p->on_rq _after_ p->state, otherwise it would
  1721. * be possible to, falsely, observe p->on_rq == 0 and get stuck
  1722. * in smp_cond_load_acquire() below.
  1723. *
  1724. * sched_ttwu_pending() try_to_wake_up()
  1725. * [S] p->on_rq = 1; [L] P->state
  1726. * UNLOCK rq->lock -----.
  1727. * \
  1728. * +--- RMB
  1729. * schedule() /
  1730. * LOCK rq->lock -----'
  1731. * UNLOCK rq->lock
  1732. *
  1733. * [task p]
  1734. * [S] p->state = UNINTERRUPTIBLE [L] p->on_rq
  1735. *
  1736. * Pairs with the UNLOCK+LOCK on rq->lock from the
  1737. * last wakeup of our task and the schedule that got our task
  1738. * current.
  1739. */
  1740. smp_rmb();
  1741. if (p->on_rq && ttwu_remote(p, wake_flags))
  1742. goto stat;
  1743. #ifdef CONFIG_SMP
  1744. /*
  1745. * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
  1746. * possible to, falsely, observe p->on_cpu == 0.
  1747. *
  1748. * One must be running (->on_cpu == 1) in order to remove oneself
  1749. * from the runqueue.
  1750. *
  1751. * [S] ->on_cpu = 1; [L] ->on_rq
  1752. * UNLOCK rq->lock
  1753. * RMB
  1754. * LOCK rq->lock
  1755. * [S] ->on_rq = 0; [L] ->on_cpu
  1756. *
  1757. * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
  1758. * from the consecutive calls to schedule(); the first switching to our
  1759. * task, the second putting it to sleep.
  1760. */
  1761. smp_rmb();
  1762. /*
  1763. * If the owning (remote) CPU is still in the middle of schedule() with
  1764. * this task as prev, wait until its done referencing the task.
  1765. *
  1766. * Pairs with the smp_store_release() in finish_task().
  1767. *
  1768. * This ensures that tasks getting woken will be fully ordered against
  1769. * their previous state and preserve Program Order.
  1770. */
  1771. smp_cond_load_acquire(&p->on_cpu, !VAL);
  1772. p->sched_contributes_to_load = !!task_contributes_to_load(p);
  1773. p->state = TASK_WAKING;
  1774. if (p->in_iowait) {
  1775. delayacct_blkio_end(p);
  1776. atomic_dec(&task_rq(p)->nr_iowait);
  1777. }
  1778. cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
  1779. if (task_cpu(p) != cpu) {
  1780. wake_flags |= WF_MIGRATED;
  1781. set_task_cpu(p, cpu);
  1782. }
  1783. #else /* CONFIG_SMP */
  1784. if (p->in_iowait) {
  1785. delayacct_blkio_end(p);
  1786. atomic_dec(&task_rq(p)->nr_iowait);
  1787. }
  1788. #endif /* CONFIG_SMP */
  1789. ttwu_queue(p, cpu, wake_flags);
  1790. stat:
  1791. ttwu_stat(p, cpu, wake_flags);
  1792. out:
  1793. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  1794. return success;
  1795. }
  1796. /**
  1797. * try_to_wake_up_local - try to wake up a local task with rq lock held
  1798. * @p: the thread to be awakened
  1799. * @rf: request-queue flags for pinning
  1800. *
  1801. * Put @p on the run-queue if it's not already there. The caller must
  1802. * ensure that this_rq() is locked, @p is bound to this_rq() and not
  1803. * the current task.
  1804. */
  1805. static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
  1806. {
  1807. struct rq *rq = task_rq(p);
  1808. if (WARN_ON_ONCE(rq != this_rq()) ||
  1809. WARN_ON_ONCE(p == current))
  1810. return;
  1811. lockdep_assert_held(&rq->lock);
  1812. if (!raw_spin_trylock(&p->pi_lock)) {
  1813. /*
  1814. * This is OK, because current is on_cpu, which avoids it being
  1815. * picked for load-balance and preemption/IRQs are still
  1816. * disabled avoiding further scheduler activity on it and we've
  1817. * not yet picked a replacement task.
  1818. */
  1819. rq_unlock(rq, rf);
  1820. raw_spin_lock(&p->pi_lock);
  1821. rq_relock(rq, rf);
  1822. }
  1823. if (!(p->state & TASK_NORMAL))
  1824. goto out;
  1825. trace_sched_waking(p);
  1826. if (!task_on_rq_queued(p)) {
  1827. if (p->in_iowait) {
  1828. delayacct_blkio_end(p);
  1829. atomic_dec(&rq->nr_iowait);
  1830. }
  1831. ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
  1832. }
  1833. ttwu_do_wakeup(rq, p, 0, rf);
  1834. ttwu_stat(p, smp_processor_id(), 0);
  1835. out:
  1836. raw_spin_unlock(&p->pi_lock);
  1837. }
  1838. /**
  1839. * wake_up_process - Wake up a specific process
  1840. * @p: The process to be woken up.
  1841. *
  1842. * Attempt to wake up the nominated process and move it to the set of runnable
  1843. * processes.
  1844. *
  1845. * Return: 1 if the process was woken up, 0 if it was already running.
  1846. *
  1847. * It may be assumed that this function implies a write memory barrier before
  1848. * changing the task state if and only if any tasks are woken up.
  1849. */
  1850. int wake_up_process(struct task_struct *p)
  1851. {
  1852. return try_to_wake_up(p, TASK_NORMAL, 0);
  1853. }
  1854. EXPORT_SYMBOL(wake_up_process);
  1855. int wake_up_state(struct task_struct *p, unsigned int state)
  1856. {
  1857. return try_to_wake_up(p, state, 0);
  1858. }
  1859. /*
  1860. * Perform scheduler related setup for a newly forked process p.
  1861. * p is forked by current.
  1862. *
  1863. * __sched_fork() is basic setup used by init_idle() too:
  1864. */
  1865. static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
  1866. {
  1867. p->on_rq = 0;
  1868. p->se.on_rq = 0;
  1869. p->se.exec_start = 0;
  1870. p->se.sum_exec_runtime = 0;
  1871. p->se.prev_sum_exec_runtime = 0;
  1872. p->se.nr_migrations = 0;
  1873. p->se.vruntime = 0;
  1874. INIT_LIST_HEAD(&p->se.group_node);
  1875. #ifdef CONFIG_FAIR_GROUP_SCHED
  1876. p->se.cfs_rq = NULL;
  1877. #endif
  1878. #ifdef CONFIG_SCHEDSTATS
  1879. /* Even if schedstat is disabled, there should not be garbage */
  1880. memset(&p->se.statistics, 0, sizeof(p->se.statistics));
  1881. #endif
  1882. RB_CLEAR_NODE(&p->dl.rb_node);
  1883. init_dl_task_timer(&p->dl);
  1884. init_dl_inactive_task_timer(&p->dl);
  1885. __dl_clear_params(p);
  1886. INIT_LIST_HEAD(&p->rt.run_list);
  1887. p->rt.timeout = 0;
  1888. p->rt.time_slice = sched_rr_timeslice;
  1889. p->rt.on_rq = 0;
  1890. p->rt.on_list = 0;
  1891. #ifdef CONFIG_PREEMPT_NOTIFIERS
  1892. INIT_HLIST_HEAD(&p->preempt_notifiers);
  1893. #endif
  1894. #ifdef CONFIG_NUMA_BALANCING
  1895. if (p->mm && atomic_read(&p->mm->mm_users) == 1) {
  1896. p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay);
  1897. p->mm->numa_scan_seq = 0;
  1898. }
  1899. if (clone_flags & CLONE_VM)
  1900. p->numa_preferred_nid = current->numa_preferred_nid;
  1901. else
  1902. p->numa_preferred_nid = -1;
  1903. p->node_stamp = 0ULL;
  1904. p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0;
  1905. p->numa_scan_period = sysctl_numa_balancing_scan_delay;
  1906. p->numa_work.next = &p->numa_work;
  1907. p->numa_faults = NULL;
  1908. p->last_task_numa_placement = 0;
  1909. p->last_sum_exec_runtime = 0;
  1910. p->numa_group = NULL;
  1911. #endif /* CONFIG_NUMA_BALANCING */
  1912. }
  1913. DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
  1914. #ifdef CONFIG_NUMA_BALANCING
  1915. void set_numabalancing_state(bool enabled)
  1916. {
  1917. if (enabled)
  1918. static_branch_enable(&sched_numa_balancing);
  1919. else
  1920. static_branch_disable(&sched_numa_balancing);
  1921. }
  1922. #ifdef CONFIG_PROC_SYSCTL
  1923. int sysctl_numa_balancing(struct ctl_table *table, int write,
  1924. void __user *buffer, size_t *lenp, loff_t *ppos)
  1925. {
  1926. struct ctl_table t;
  1927. int err;
  1928. int state = static_branch_likely(&sched_numa_balancing);
  1929. if (write && !capable(CAP_SYS_ADMIN))
  1930. return -EPERM;
  1931. t = *table;
  1932. t.data = &state;
  1933. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  1934. if (err < 0)
  1935. return err;
  1936. if (write)
  1937. set_numabalancing_state(state);
  1938. return err;
  1939. }
  1940. #endif
  1941. #endif
  1942. #ifdef CONFIG_SCHEDSTATS
  1943. DEFINE_STATIC_KEY_FALSE(sched_schedstats);
  1944. static bool __initdata __sched_schedstats = false;
  1945. static void set_schedstats(bool enabled)
  1946. {
  1947. if (enabled)
  1948. static_branch_enable(&sched_schedstats);
  1949. else
  1950. static_branch_disable(&sched_schedstats);
  1951. }
  1952. void force_schedstat_enabled(void)
  1953. {
  1954. if (!schedstat_enabled()) {
  1955. pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
  1956. static_branch_enable(&sched_schedstats);
  1957. }
  1958. }
  1959. static int __init setup_schedstats(char *str)
  1960. {
  1961. int ret = 0;
  1962. if (!str)
  1963. goto out;
  1964. /*
  1965. * This code is called before jump labels have been set up, so we can't
  1966. * change the static branch directly just yet. Instead set a temporary
  1967. * variable so init_schedstats() can do it later.
  1968. */
  1969. if (!strcmp(str, "enable")) {
  1970. __sched_schedstats = true;
  1971. ret = 1;
  1972. } else if (!strcmp(str, "disable")) {
  1973. __sched_schedstats = false;
  1974. ret = 1;
  1975. }
  1976. out:
  1977. if (!ret)
  1978. pr_warn("Unable to parse schedstats=\n");
  1979. return ret;
  1980. }
  1981. __setup("schedstats=", setup_schedstats);
  1982. static void __init init_schedstats(void)
  1983. {
  1984. set_schedstats(__sched_schedstats);
  1985. }
  1986. #ifdef CONFIG_PROC_SYSCTL
  1987. int sysctl_schedstats(struct ctl_table *table, int write,
  1988. void __user *buffer, size_t *lenp, loff_t *ppos)
  1989. {
  1990. struct ctl_table t;
  1991. int err;
  1992. int state = static_branch_likely(&sched_schedstats);
  1993. if (write && !capable(CAP_SYS_ADMIN))
  1994. return -EPERM;
  1995. t = *table;
  1996. t.data = &state;
  1997. err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
  1998. if (err < 0)
  1999. return err;
  2000. if (write)
  2001. set_schedstats(state);
  2002. return err;
  2003. }
  2004. #endif /* CONFIG_PROC_SYSCTL */
  2005. #else /* !CONFIG_SCHEDSTATS */
  2006. static inline void init_schedstats(void) {}
  2007. #endif /* CONFIG_SCHEDSTATS */
  2008. /*
  2009. * fork()/clone()-time setup:
  2010. */
  2011. int sched_fork(unsigned long clone_flags, struct task_struct *p)
  2012. {
  2013. unsigned long flags;
  2014. int cpu = get_cpu();
  2015. __sched_fork(clone_flags, p);
  2016. /*
  2017. * We mark the process as NEW here. This guarantees that
  2018. * nobody will actually run it, and a signal or other external
  2019. * event cannot wake it up and insert it on the runqueue either.
  2020. */
  2021. p->state = TASK_NEW;
  2022. /*
  2023. * Make sure we do not leak PI boosting priority to the child.
  2024. */
  2025. p->prio = current->normal_prio;
  2026. /*
  2027. * Revert to default priority/policy on fork if requested.
  2028. */
  2029. if (unlikely(p->sched_reset_on_fork)) {
  2030. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  2031. p->policy = SCHED_NORMAL;
  2032. p->static_prio = NICE_TO_PRIO(0);
  2033. p->rt_priority = 0;
  2034. } else if (PRIO_TO_NICE(p->static_prio) < 0)
  2035. p->static_prio = NICE_TO_PRIO(0);
  2036. p->prio = p->normal_prio = __normal_prio(p);
  2037. set_load_weight(p, false);
  2038. /*
  2039. * We don't need the reset flag anymore after the fork. It has
  2040. * fulfilled its duty:
  2041. */
  2042. p->sched_reset_on_fork = 0;
  2043. }
  2044. if (dl_prio(p->prio)) {
  2045. put_cpu();
  2046. return -EAGAIN;
  2047. } else if (rt_prio(p->prio)) {
  2048. p->sched_class = &rt_sched_class;
  2049. } else {
  2050. p->sched_class = &fair_sched_class;
  2051. }
  2052. init_entity_runnable_average(&p->se);
  2053. /*
  2054. * The child is not yet in the pid-hash so no cgroup attach races,
  2055. * and the cgroup is pinned to this child due to cgroup_fork()
  2056. * is ran before sched_fork().
  2057. *
  2058. * Silence PROVE_RCU.
  2059. */
  2060. raw_spin_lock_irqsave(&p->pi_lock, flags);
  2061. /*
  2062. * We're setting the CPU for the first time, we don't migrate,
  2063. * so use __set_task_cpu().
  2064. */
  2065. __set_task_cpu(p, cpu);
  2066. if (p->sched_class->task_fork)
  2067. p->sched_class->task_fork(p);
  2068. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  2069. #ifdef CONFIG_SCHED_INFO
  2070. if (likely(sched_info_on()))
  2071. memset(&p->sched_info, 0, sizeof(p->sched_info));
  2072. #endif
  2073. #if defined(CONFIG_SMP)
  2074. p->on_cpu = 0;
  2075. #endif
  2076. init_task_preempt_count(p);
  2077. #ifdef CONFIG_SMP
  2078. plist_node_init(&p->pushable_tasks, MAX_PRIO);
  2079. RB_CLEAR_NODE(&p->pushable_dl_tasks);
  2080. #endif
  2081. put_cpu();
  2082. return 0;
  2083. }
  2084. unsigned long to_ratio(u64 period, u64 runtime)
  2085. {
  2086. if (runtime == RUNTIME_INF)
  2087. return BW_UNIT;
  2088. /*
  2089. * Doing this here saves a lot of checks in all
  2090. * the calling paths, and returning zero seems
  2091. * safe for them anyway.
  2092. */
  2093. if (period == 0)
  2094. return 0;
  2095. return div64_u64(runtime << BW_SHIFT, period);
  2096. }
  2097. /*
  2098. * wake_up_new_task - wake up a newly created task for the first time.
  2099. *
  2100. * This function will do some initial scheduler statistics housekeeping
  2101. * that must be done for every newly created context, then puts the task
  2102. * on the runqueue and wakes it.
  2103. */
  2104. void wake_up_new_task(struct task_struct *p)
  2105. {
  2106. struct rq_flags rf;
  2107. struct rq *rq;
  2108. raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
  2109. p->state = TASK_RUNNING;
  2110. #ifdef CONFIG_SMP
  2111. /*
  2112. * Fork balancing, do it here and not earlier because:
  2113. * - cpus_allowed can change in the fork path
  2114. * - any previously selected CPU might disappear through hotplug
  2115. *
  2116. * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
  2117. * as we're not fully set-up yet.
  2118. */
  2119. p->recent_used_cpu = task_cpu(p);
  2120. __set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
  2121. #endif
  2122. rq = __task_rq_lock(p, &rf);
  2123. update_rq_clock(rq);
  2124. post_init_entity_util_avg(&p->se);
  2125. activate_task(rq, p, ENQUEUE_NOCLOCK);
  2126. p->on_rq = TASK_ON_RQ_QUEUED;
  2127. trace_sched_wakeup_new(p);
  2128. check_preempt_curr(rq, p, WF_FORK);
  2129. #ifdef CONFIG_SMP
  2130. if (p->sched_class->task_woken) {
  2131. /*
  2132. * Nothing relies on rq->lock after this, so its fine to
  2133. * drop it.
  2134. */
  2135. rq_unpin_lock(rq, &rf);
  2136. p->sched_class->task_woken(rq, p);
  2137. rq_repin_lock(rq, &rf);
  2138. }
  2139. #endif
  2140. task_rq_unlock(rq, p, &rf);
  2141. }
  2142. #ifdef CONFIG_PREEMPT_NOTIFIERS
  2143. static struct static_key preempt_notifier_key = STATIC_KEY_INIT_FALSE;
  2144. void preempt_notifier_inc(void)
  2145. {
  2146. static_key_slow_inc(&preempt_notifier_key);
  2147. }
  2148. EXPORT_SYMBOL_GPL(preempt_notifier_inc);
  2149. void preempt_notifier_dec(void)
  2150. {
  2151. static_key_slow_dec(&preempt_notifier_key);
  2152. }
  2153. EXPORT_SYMBOL_GPL(preempt_notifier_dec);
  2154. /**
  2155. * preempt_notifier_register - tell me when current is being preempted & rescheduled
  2156. * @notifier: notifier struct to register
  2157. */
  2158. void preempt_notifier_register(struct preempt_notifier *notifier)
  2159. {
  2160. if (!static_key_false(&preempt_notifier_key))
  2161. WARN(1, "registering preempt_notifier while notifiers disabled\n");
  2162. hlist_add_head(&notifier->link, &current->preempt_notifiers);
  2163. }
  2164. EXPORT_SYMBOL_GPL(preempt_notifier_register);
  2165. /**
  2166. * preempt_notifier_unregister - no longer interested in preemption notifications
  2167. * @notifier: notifier struct to unregister
  2168. *
  2169. * This is *not* safe to call from within a preemption notifier.
  2170. */
  2171. void preempt_notifier_unregister(struct preempt_notifier *notifier)
  2172. {
  2173. hlist_del(&notifier->link);
  2174. }
  2175. EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
  2176. static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2177. {
  2178. struct preempt_notifier *notifier;
  2179. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  2180. notifier->ops->sched_in(notifier, raw_smp_processor_id());
  2181. }
  2182. static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2183. {
  2184. if (static_key_false(&preempt_notifier_key))
  2185. __fire_sched_in_preempt_notifiers(curr);
  2186. }
  2187. static void
  2188. __fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2189. struct task_struct *next)
  2190. {
  2191. struct preempt_notifier *notifier;
  2192. hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
  2193. notifier->ops->sched_out(notifier, next);
  2194. }
  2195. static __always_inline void
  2196. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2197. struct task_struct *next)
  2198. {
  2199. if (static_key_false(&preempt_notifier_key))
  2200. __fire_sched_out_preempt_notifiers(curr, next);
  2201. }
  2202. #else /* !CONFIG_PREEMPT_NOTIFIERS */
  2203. static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
  2204. {
  2205. }
  2206. static inline void
  2207. fire_sched_out_preempt_notifiers(struct task_struct *curr,
  2208. struct task_struct *next)
  2209. {
  2210. }
  2211. #endif /* CONFIG_PREEMPT_NOTIFIERS */
  2212. static inline void prepare_task(struct task_struct *next)
  2213. {
  2214. #ifdef CONFIG_SMP
  2215. /*
  2216. * Claim the task as running, we do this before switching to it
  2217. * such that any running task will have this set.
  2218. */
  2219. next->on_cpu = 1;
  2220. #endif
  2221. }
  2222. static inline void finish_task(struct task_struct *prev)
  2223. {
  2224. #ifdef CONFIG_SMP
  2225. /*
  2226. * After ->on_cpu is cleared, the task can be moved to a different CPU.
  2227. * We must ensure this doesn't happen until the switch is completely
  2228. * finished.
  2229. *
  2230. * In particular, the load of prev->state in finish_task_switch() must
  2231. * happen before this.
  2232. *
  2233. * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
  2234. */
  2235. smp_store_release(&prev->on_cpu, 0);
  2236. #endif
  2237. }
  2238. static inline void
  2239. prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
  2240. {
  2241. /*
  2242. * Since the runqueue lock will be released by the next
  2243. * task (which is an invalid locking op but in the case
  2244. * of the scheduler it's an obvious special-case), so we
  2245. * do an early lockdep release here:
  2246. */
  2247. rq_unpin_lock(rq, rf);
  2248. spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
  2249. #ifdef CONFIG_DEBUG_SPINLOCK
  2250. /* this is a valid case when another task releases the spinlock */
  2251. rq->lock.owner = next;
  2252. #endif
  2253. }
  2254. static inline void finish_lock_switch(struct rq *rq)
  2255. {
  2256. /*
  2257. * If we are tracking spinlock dependencies then we have to
  2258. * fix up the runqueue lock - which gets 'carried over' from
  2259. * prev into current:
  2260. */
  2261. spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
  2262. raw_spin_unlock_irq(&rq->lock);
  2263. }
  2264. /**
  2265. * prepare_task_switch - prepare to switch tasks
  2266. * @rq: the runqueue preparing to switch
  2267. * @prev: the current task that is being switched out
  2268. * @next: the task we are going to switch to.
  2269. *
  2270. * This is called with the rq lock held and interrupts off. It must
  2271. * be paired with a subsequent finish_task_switch after the context
  2272. * switch.
  2273. *
  2274. * prepare_task_switch sets up locking and calls architecture specific
  2275. * hooks.
  2276. */
  2277. static inline void
  2278. prepare_task_switch(struct rq *rq, struct task_struct *prev,
  2279. struct task_struct *next)
  2280. {
  2281. sched_info_switch(rq, prev, next);
  2282. perf_event_task_sched_out(prev, next);
  2283. fire_sched_out_preempt_notifiers(prev, next);
  2284. prepare_task(next);
  2285. prepare_arch_switch(next);
  2286. }
  2287. /**
  2288. * finish_task_switch - clean up after a task-switch
  2289. * @prev: the thread we just switched away from.
  2290. *
  2291. * finish_task_switch must be called after the context switch, paired
  2292. * with a prepare_task_switch call before the context switch.
  2293. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  2294. * and do any other architecture-specific cleanup actions.
  2295. *
  2296. * Note that we may have delayed dropping an mm in context_switch(). If
  2297. * so, we finish that here outside of the runqueue lock. (Doing it
  2298. * with the lock held can cause deadlocks; see schedule() for
  2299. * details.)
  2300. *
  2301. * The context switch have flipped the stack from under us and restored the
  2302. * local variables which were saved when this task called schedule() in the
  2303. * past. prev == current is still correct but we need to recalculate this_rq
  2304. * because prev may have moved to another CPU.
  2305. */
  2306. static struct rq *finish_task_switch(struct task_struct *prev)
  2307. __releases(rq->lock)
  2308. {
  2309. struct rq *rq = this_rq();
  2310. struct mm_struct *mm = rq->prev_mm;
  2311. long prev_state;
  2312. /*
  2313. * The previous task will have left us with a preempt_count of 2
  2314. * because it left us after:
  2315. *
  2316. * schedule()
  2317. * preempt_disable(); // 1
  2318. * __schedule()
  2319. * raw_spin_lock_irq(&rq->lock) // 2
  2320. *
  2321. * Also, see FORK_PREEMPT_COUNT.
  2322. */
  2323. if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
  2324. "corrupted preempt_count: %s/%d/0x%x\n",
  2325. current->comm, current->pid, preempt_count()))
  2326. preempt_count_set(FORK_PREEMPT_COUNT);
  2327. rq->prev_mm = NULL;
  2328. /*
  2329. * A task struct has one reference for the use as "current".
  2330. * If a task dies, then it sets TASK_DEAD in tsk->state and calls
  2331. * schedule one last time. The schedule call will never return, and
  2332. * the scheduled task must drop that reference.
  2333. *
  2334. * We must observe prev->state before clearing prev->on_cpu (in
  2335. * finish_task), otherwise a concurrent wakeup can get prev
  2336. * running on another CPU and we could rave with its RUNNING -> DEAD
  2337. * transition, resulting in a double drop.
  2338. */
  2339. prev_state = prev->state;
  2340. vtime_task_switch(prev);
  2341. perf_event_task_sched_in(prev, current);
  2342. finish_task(prev);
  2343. finish_lock_switch(rq);
  2344. finish_arch_post_lock_switch();
  2345. fire_sched_in_preempt_notifiers(current);
  2346. /*
  2347. * When switching through a kernel thread, the loop in
  2348. * membarrier_{private,global}_expedited() may have observed that
  2349. * kernel thread and not issued an IPI. It is therefore possible to
  2350. * schedule between user->kernel->user threads without passing though
  2351. * switch_mm(). Membarrier requires a barrier after storing to
  2352. * rq->curr, before returning to userspace, so provide them here:
  2353. *
  2354. * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
  2355. * provided by mmdrop(),
  2356. * - a sync_core for SYNC_CORE.
  2357. */
  2358. if (mm) {
  2359. membarrier_mm_sync_core_before_usermode(mm);
  2360. mmdrop(mm);
  2361. }
  2362. if (unlikely(prev_state == TASK_DEAD)) {
  2363. if (prev->sched_class->task_dead)
  2364. prev->sched_class->task_dead(prev);
  2365. /*
  2366. * Remove function-return probe instances associated with this
  2367. * task and put them back on the free list.
  2368. */
  2369. kprobe_flush_task(prev);
  2370. /* Task is done with its stack. */
  2371. put_task_stack(prev);
  2372. put_task_struct(prev);
  2373. }
  2374. tick_nohz_task_switch();
  2375. return rq;
  2376. }
  2377. #ifdef CONFIG_SMP
  2378. /* rq->lock is NOT held, but preemption is disabled */
  2379. static void __balance_callback(struct rq *rq)
  2380. {
  2381. struct callback_head *head, *next;
  2382. void (*func)(struct rq *rq);
  2383. unsigned long flags;
  2384. raw_spin_lock_irqsave(&rq->lock, flags);
  2385. head = rq->balance_callback;
  2386. rq->balance_callback = NULL;
  2387. while (head) {
  2388. func = (void (*)(struct rq *))head->func;
  2389. next = head->next;
  2390. head->next = NULL;
  2391. head = next;
  2392. func(rq);
  2393. }
  2394. raw_spin_unlock_irqrestore(&rq->lock, flags);
  2395. }
  2396. static inline void balance_callback(struct rq *rq)
  2397. {
  2398. if (unlikely(rq->balance_callback))
  2399. __balance_callback(rq);
  2400. }
  2401. #else
  2402. static inline void balance_callback(struct rq *rq)
  2403. {
  2404. }
  2405. #endif
  2406. /**
  2407. * schedule_tail - first thing a freshly forked thread must call.
  2408. * @prev: the thread we just switched away from.
  2409. */
  2410. asmlinkage __visible void schedule_tail(struct task_struct *prev)
  2411. __releases(rq->lock)
  2412. {
  2413. struct rq *rq;
  2414. /*
  2415. * New tasks start with FORK_PREEMPT_COUNT, see there and
  2416. * finish_task_switch() for details.
  2417. *
  2418. * finish_task_switch() will drop rq->lock() and lower preempt_count
  2419. * and the preempt_enable() will end up enabling preemption (on
  2420. * PREEMPT_COUNT kernels).
  2421. */
  2422. rq = finish_task_switch(prev);
  2423. balance_callback(rq);
  2424. preempt_enable();
  2425. if (current->set_child_tid)
  2426. put_user(task_pid_vnr(current), current->set_child_tid);
  2427. }
  2428. /*
  2429. * context_switch - switch to the new MM and the new thread's register state.
  2430. */
  2431. static __always_inline struct rq *
  2432. context_switch(struct rq *rq, struct task_struct *prev,
  2433. struct task_struct *next, struct rq_flags *rf)
  2434. {
  2435. struct mm_struct *mm, *oldmm;
  2436. prepare_task_switch(rq, prev, next);
  2437. mm = next->mm;
  2438. oldmm = prev->active_mm;
  2439. /*
  2440. * For paravirt, this is coupled with an exit in switch_to to
  2441. * combine the page table reload and the switch backend into
  2442. * one hypercall.
  2443. */
  2444. arch_start_context_switch(prev);
  2445. /*
  2446. * If mm is non-NULL, we pass through switch_mm(). If mm is
  2447. * NULL, we will pass through mmdrop() in finish_task_switch().
  2448. * Both of these contain the full memory barrier required by
  2449. * membarrier after storing to rq->curr, before returning to
  2450. * user-space.
  2451. */
  2452. if (!mm) {
  2453. next->active_mm = oldmm;
  2454. mmgrab(oldmm);
  2455. enter_lazy_tlb(oldmm, next);
  2456. } else
  2457. switch_mm_irqs_off(oldmm, mm, next);
  2458. if (!prev->mm) {
  2459. prev->active_mm = NULL;
  2460. rq->prev_mm = oldmm;
  2461. }
  2462. rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
  2463. prepare_lock_switch(rq, next, rf);
  2464. /* Here we just switch the register state and the stack. */
  2465. switch_to(prev, next, prev);
  2466. barrier();
  2467. return finish_task_switch(prev);
  2468. }
  2469. /*
  2470. * nr_running and nr_context_switches:
  2471. *
  2472. * externally visible scheduler statistics: current number of runnable
  2473. * threads, total number of context switches performed since bootup.
  2474. */
  2475. unsigned long nr_running(void)
  2476. {
  2477. unsigned long i, sum = 0;
  2478. for_each_online_cpu(i)
  2479. sum += cpu_rq(i)->nr_running;
  2480. return sum;
  2481. }
  2482. /*
  2483. * Check if only the current task is running on the CPU.
  2484. *
  2485. * Caution: this function does not check that the caller has disabled
  2486. * preemption, thus the result might have a time-of-check-to-time-of-use
  2487. * race. The caller is responsible to use it correctly, for example:
  2488. *
  2489. * - from a non-preemptable section (of course)
  2490. *
  2491. * - from a thread that is bound to a single CPU
  2492. *
  2493. * - in a loop with very short iterations (e.g. a polling loop)
  2494. */
  2495. bool single_task_running(void)
  2496. {
  2497. return raw_rq()->nr_running == 1;
  2498. }
  2499. EXPORT_SYMBOL(single_task_running);
  2500. unsigned long long nr_context_switches(void)
  2501. {
  2502. int i;
  2503. unsigned long long sum = 0;
  2504. for_each_possible_cpu(i)
  2505. sum += cpu_rq(i)->nr_switches;
  2506. return sum;
  2507. }
  2508. /*
  2509. * IO-wait accounting, and how its mostly bollocks (on SMP).
  2510. *
  2511. * The idea behind IO-wait account is to account the idle time that we could
  2512. * have spend running if it were not for IO. That is, if we were to improve the
  2513. * storage performance, we'd have a proportional reduction in IO-wait time.
  2514. *
  2515. * This all works nicely on UP, where, when a task blocks on IO, we account
  2516. * idle time as IO-wait, because if the storage were faster, it could've been
  2517. * running and we'd not be idle.
  2518. *
  2519. * This has been extended to SMP, by doing the same for each CPU. This however
  2520. * is broken.
  2521. *
  2522. * Imagine for instance the case where two tasks block on one CPU, only the one
  2523. * CPU will have IO-wait accounted, while the other has regular idle. Even
  2524. * though, if the storage were faster, both could've ran at the same time,
  2525. * utilising both CPUs.
  2526. *
  2527. * This means, that when looking globally, the current IO-wait accounting on
  2528. * SMP is a lower bound, by reason of under accounting.
  2529. *
  2530. * Worse, since the numbers are provided per CPU, they are sometimes
  2531. * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
  2532. * associated with any one particular CPU, it can wake to another CPU than it
  2533. * blocked on. This means the per CPU IO-wait number is meaningless.
  2534. *
  2535. * Task CPU affinities can make all that even more 'interesting'.
  2536. */
  2537. unsigned long nr_iowait(void)
  2538. {
  2539. unsigned long i, sum = 0;
  2540. for_each_possible_cpu(i)
  2541. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  2542. return sum;
  2543. }
  2544. /*
  2545. * Consumers of these two interfaces, like for example the cpufreq menu
  2546. * governor are using nonsensical data. Boosting frequency for a CPU that has
  2547. * IO-wait which might not even end up running the task when it does become
  2548. * runnable.
  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. struct rq_flags rf;
  2655. sched_clock_tick();
  2656. rq_lock(rq, &rf);
  2657. update_rq_clock(rq);
  2658. curr->sched_class->task_tick(rq, curr, 0);
  2659. cpu_load_update_active(rq);
  2660. calc_global_load_tick(rq);
  2661. rq_unlock(rq, &rf);
  2662. perf_event_task_tick();
  2663. #ifdef CONFIG_SMP
  2664. rq->idle_balance = idle_cpu(cpu);
  2665. trigger_load_balance(rq);
  2666. #endif
  2667. }
  2668. #ifdef CONFIG_NO_HZ_FULL
  2669. struct tick_work {
  2670. int cpu;
  2671. struct delayed_work work;
  2672. };
  2673. static struct tick_work __percpu *tick_work_cpu;
  2674. static void sched_tick_remote(struct work_struct *work)
  2675. {
  2676. struct delayed_work *dwork = to_delayed_work(work);
  2677. struct tick_work *twork = container_of(dwork, struct tick_work, work);
  2678. int cpu = twork->cpu;
  2679. struct rq *rq = cpu_rq(cpu);
  2680. struct rq_flags rf;
  2681. /*
  2682. * Handle the tick only if it appears the remote CPU is running in full
  2683. * dynticks mode. The check is racy by nature, but missing a tick or
  2684. * having one too much is no big deal because the scheduler tick updates
  2685. * statistics and checks timeslices in a time-independent way, regardless
  2686. * of when exactly it is running.
  2687. */
  2688. if (!idle_cpu(cpu) && tick_nohz_tick_stopped_cpu(cpu)) {
  2689. struct task_struct *curr;
  2690. u64 delta;
  2691. rq_lock_irq(rq, &rf);
  2692. update_rq_clock(rq);
  2693. curr = rq->curr;
  2694. delta = rq_clock_task(rq) - curr->se.exec_start;
  2695. /*
  2696. * Make sure the next tick runs within a reasonable
  2697. * amount of time.
  2698. */
  2699. WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
  2700. curr->sched_class->task_tick(rq, curr, 0);
  2701. rq_unlock_irq(rq, &rf);
  2702. }
  2703. /*
  2704. * Run the remote tick once per second (1Hz). This arbitrary
  2705. * frequency is large enough to avoid overload but short enough
  2706. * to keep scheduler internal stats reasonably up to date.
  2707. */
  2708. queue_delayed_work(system_unbound_wq, dwork, HZ);
  2709. }
  2710. static void sched_tick_start(int cpu)
  2711. {
  2712. struct tick_work *twork;
  2713. if (housekeeping_cpu(cpu, HK_FLAG_TICK))
  2714. return;
  2715. WARN_ON_ONCE(!tick_work_cpu);
  2716. twork = per_cpu_ptr(tick_work_cpu, cpu);
  2717. twork->cpu = cpu;
  2718. INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
  2719. queue_delayed_work(system_unbound_wq, &twork->work, HZ);
  2720. }
  2721. #ifdef CONFIG_HOTPLUG_CPU
  2722. static void sched_tick_stop(int cpu)
  2723. {
  2724. struct tick_work *twork;
  2725. if (housekeeping_cpu(cpu, HK_FLAG_TICK))
  2726. return;
  2727. WARN_ON_ONCE(!tick_work_cpu);
  2728. twork = per_cpu_ptr(tick_work_cpu, cpu);
  2729. cancel_delayed_work_sync(&twork->work);
  2730. }
  2731. #endif /* CONFIG_HOTPLUG_CPU */
  2732. int __init sched_tick_offload_init(void)
  2733. {
  2734. tick_work_cpu = alloc_percpu(struct tick_work);
  2735. BUG_ON(!tick_work_cpu);
  2736. return 0;
  2737. }
  2738. #else /* !CONFIG_NO_HZ_FULL */
  2739. static inline void sched_tick_start(int cpu) { }
  2740. static inline void sched_tick_stop(int cpu) { }
  2741. #endif
  2742. #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
  2743. defined(CONFIG_PREEMPT_TRACER))
  2744. /*
  2745. * If the value passed in is equal to the current preempt count
  2746. * then we just disabled preemption. Start timing the latency.
  2747. */
  2748. static inline void preempt_latency_start(int val)
  2749. {
  2750. if (preempt_count() == val) {
  2751. unsigned long ip = get_lock_parent_ip();
  2752. #ifdef CONFIG_DEBUG_PREEMPT
  2753. current->preempt_disable_ip = ip;
  2754. #endif
  2755. trace_preempt_off(CALLER_ADDR0, ip);
  2756. }
  2757. }
  2758. void preempt_count_add(int val)
  2759. {
  2760. #ifdef CONFIG_DEBUG_PREEMPT
  2761. /*
  2762. * Underflow?
  2763. */
  2764. if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
  2765. return;
  2766. #endif
  2767. __preempt_count_add(val);
  2768. #ifdef CONFIG_DEBUG_PREEMPT
  2769. /*
  2770. * Spinlock count overflowing soon?
  2771. */
  2772. DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
  2773. PREEMPT_MASK - 10);
  2774. #endif
  2775. preempt_latency_start(val);
  2776. }
  2777. EXPORT_SYMBOL(preempt_count_add);
  2778. NOKPROBE_SYMBOL(preempt_count_add);
  2779. /*
  2780. * If the value passed in equals to the current preempt count
  2781. * then we just enabled preemption. Stop timing the latency.
  2782. */
  2783. static inline void preempt_latency_stop(int val)
  2784. {
  2785. if (preempt_count() == val)
  2786. trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
  2787. }
  2788. void preempt_count_sub(int val)
  2789. {
  2790. #ifdef CONFIG_DEBUG_PREEMPT
  2791. /*
  2792. * Underflow?
  2793. */
  2794. if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
  2795. return;
  2796. /*
  2797. * Is the spinlock portion underflowing?
  2798. */
  2799. if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
  2800. !(preempt_count() & PREEMPT_MASK)))
  2801. return;
  2802. #endif
  2803. preempt_latency_stop(val);
  2804. __preempt_count_sub(val);
  2805. }
  2806. EXPORT_SYMBOL(preempt_count_sub);
  2807. NOKPROBE_SYMBOL(preempt_count_sub);
  2808. #else
  2809. static inline void preempt_latency_start(int val) { }
  2810. static inline void preempt_latency_stop(int val) { }
  2811. #endif
  2812. static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
  2813. {
  2814. #ifdef CONFIG_DEBUG_PREEMPT
  2815. return p->preempt_disable_ip;
  2816. #else
  2817. return 0;
  2818. #endif
  2819. }
  2820. /*
  2821. * Print scheduling while atomic bug:
  2822. */
  2823. static noinline void __schedule_bug(struct task_struct *prev)
  2824. {
  2825. /* Save this before calling printk(), since that will clobber it */
  2826. unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
  2827. if (oops_in_progress)
  2828. return;
  2829. printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
  2830. prev->comm, prev->pid, preempt_count());
  2831. debug_show_held_locks(prev);
  2832. print_modules();
  2833. if (irqs_disabled())
  2834. print_irqtrace_events(prev);
  2835. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  2836. && in_atomic_preempt_off()) {
  2837. pr_err("Preemption disabled at:");
  2838. print_ip_sym(preempt_disable_ip);
  2839. pr_cont("\n");
  2840. }
  2841. if (panic_on_warn)
  2842. panic("scheduling while atomic\n");
  2843. dump_stack();
  2844. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  2845. }
  2846. /*
  2847. * Various schedule()-time debugging checks and statistics:
  2848. */
  2849. static inline void schedule_debug(struct task_struct *prev)
  2850. {
  2851. #ifdef CONFIG_SCHED_STACK_END_CHECK
  2852. if (task_stack_end_corrupted(prev))
  2853. panic("corrupted stack end detected inside scheduler\n");
  2854. #endif
  2855. if (unlikely(in_atomic_preempt_off())) {
  2856. __schedule_bug(prev);
  2857. preempt_count_set(PREEMPT_DISABLED);
  2858. }
  2859. rcu_sleep_check();
  2860. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2861. schedstat_inc(this_rq()->sched_count);
  2862. }
  2863. /*
  2864. * Pick up the highest-prio task:
  2865. */
  2866. static inline struct task_struct *
  2867. pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
  2868. {
  2869. const struct sched_class *class;
  2870. struct task_struct *p;
  2871. /*
  2872. * Optimization: we know that if all tasks are in the fair class we can
  2873. * call that function directly, but only if the @prev task wasn't of a
  2874. * higher scheduling class, because otherwise those loose the
  2875. * opportunity to pull in more work from other CPUs.
  2876. */
  2877. if (likely((prev->sched_class == &idle_sched_class ||
  2878. prev->sched_class == &fair_sched_class) &&
  2879. rq->nr_running == rq->cfs.h_nr_running)) {
  2880. p = fair_sched_class.pick_next_task(rq, prev, rf);
  2881. if (unlikely(p == RETRY_TASK))
  2882. goto again;
  2883. /* Assumes fair_sched_class->next == idle_sched_class */
  2884. if (unlikely(!p))
  2885. p = idle_sched_class.pick_next_task(rq, prev, rf);
  2886. return p;
  2887. }
  2888. again:
  2889. for_each_class(class) {
  2890. p = class->pick_next_task(rq, prev, rf);
  2891. if (p) {
  2892. if (unlikely(p == RETRY_TASK))
  2893. goto again;
  2894. return p;
  2895. }
  2896. }
  2897. /* The idle class should always have a runnable task: */
  2898. BUG();
  2899. }
  2900. /*
  2901. * __schedule() is the main scheduler function.
  2902. *
  2903. * The main means of driving the scheduler and thus entering this function are:
  2904. *
  2905. * 1. Explicit blocking: mutex, semaphore, waitqueue, etc.
  2906. *
  2907. * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
  2908. * paths. For example, see arch/x86/entry_64.S.
  2909. *
  2910. * To drive preemption between tasks, the scheduler sets the flag in timer
  2911. * interrupt handler scheduler_tick().
  2912. *
  2913. * 3. Wakeups don't really cause entry into schedule(). They add a
  2914. * task to the run-queue and that's it.
  2915. *
  2916. * Now, if the new task added to the run-queue preempts the current
  2917. * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
  2918. * called on the nearest possible occasion:
  2919. *
  2920. * - If the kernel is preemptible (CONFIG_PREEMPT=y):
  2921. *
  2922. * - in syscall or exception context, at the next outmost
  2923. * preempt_enable(). (this might be as soon as the wake_up()'s
  2924. * spin_unlock()!)
  2925. *
  2926. * - in IRQ context, return from interrupt-handler to
  2927. * preemptible context
  2928. *
  2929. * - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
  2930. * then at the next:
  2931. *
  2932. * - cond_resched() call
  2933. * - explicit schedule() call
  2934. * - return from syscall or exception to user-space
  2935. * - return from interrupt-handler to user-space
  2936. *
  2937. * WARNING: must be called with preemption disabled!
  2938. */
  2939. static void __sched notrace __schedule(bool preempt)
  2940. {
  2941. struct task_struct *prev, *next;
  2942. unsigned long *switch_count;
  2943. struct rq_flags rf;
  2944. struct rq *rq;
  2945. int cpu;
  2946. cpu = smp_processor_id();
  2947. rq = cpu_rq(cpu);
  2948. prev = rq->curr;
  2949. schedule_debug(prev);
  2950. if (sched_feat(HRTICK))
  2951. hrtick_clear(rq);
  2952. local_irq_disable();
  2953. rcu_note_context_switch(preempt);
  2954. /*
  2955. * Make sure that signal_pending_state()->signal_pending() below
  2956. * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
  2957. * done by the caller to avoid the race with signal_wake_up().
  2958. *
  2959. * The membarrier system call requires a full memory barrier
  2960. * after coming from user-space, before storing to rq->curr.
  2961. */
  2962. rq_lock(rq, &rf);
  2963. smp_mb__after_spinlock();
  2964. /* Promote REQ to ACT */
  2965. rq->clock_update_flags <<= 1;
  2966. update_rq_clock(rq);
  2967. switch_count = &prev->nivcsw;
  2968. if (!preempt && prev->state) {
  2969. if (unlikely(signal_pending_state(prev->state, prev))) {
  2970. prev->state = TASK_RUNNING;
  2971. } else {
  2972. deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
  2973. prev->on_rq = 0;
  2974. if (prev->in_iowait) {
  2975. atomic_inc(&rq->nr_iowait);
  2976. delayacct_blkio_start();
  2977. }
  2978. /*
  2979. * If a worker went to sleep, notify and ask workqueue
  2980. * whether it wants to wake up a task to maintain
  2981. * concurrency.
  2982. */
  2983. if (prev->flags & PF_WQ_WORKER) {
  2984. struct task_struct *to_wakeup;
  2985. to_wakeup = wq_worker_sleeping(prev);
  2986. if (to_wakeup)
  2987. try_to_wake_up_local(to_wakeup, &rf);
  2988. }
  2989. }
  2990. switch_count = &prev->nvcsw;
  2991. }
  2992. next = pick_next_task(rq, prev, &rf);
  2993. clear_tsk_need_resched(prev);
  2994. clear_preempt_need_resched();
  2995. if (likely(prev != next)) {
  2996. rq->nr_switches++;
  2997. rq->curr = next;
  2998. /*
  2999. * The membarrier system call requires each architecture
  3000. * to have a full memory barrier after updating
  3001. * rq->curr, before returning to user-space.
  3002. *
  3003. * Here are the schemes providing that barrier on the
  3004. * various architectures:
  3005. * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
  3006. * switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
  3007. * - finish_lock_switch() for weakly-ordered
  3008. * architectures where spin_unlock is a full barrier,
  3009. * - switch_to() for arm64 (weakly-ordered, spin_unlock
  3010. * is a RELEASE barrier),
  3011. */
  3012. ++*switch_count;
  3013. trace_sched_switch(preempt, prev, next);
  3014. /* Also unlocks the rq: */
  3015. rq = context_switch(rq, prev, next, &rf);
  3016. } else {
  3017. rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
  3018. rq_unlock_irq(rq, &rf);
  3019. }
  3020. balance_callback(rq);
  3021. }
  3022. void __noreturn do_task_dead(void)
  3023. {
  3024. /*
  3025. * The setting of TASK_RUNNING by try_to_wake_up() may be delayed
  3026. * when the following two conditions become true.
  3027. * - There is race condition of mmap_sem (It is acquired by
  3028. * exit_mm()), and
  3029. * - SMI occurs before setting TASK_RUNINNG.
  3030. * (or hypervisor of virtual machine switches to other guest)
  3031. * As a result, we may become TASK_RUNNING after becoming TASK_DEAD
  3032. *
  3033. * To avoid it, we have to wait for releasing tsk->pi_lock which
  3034. * is held by try_to_wake_up()
  3035. */
  3036. raw_spin_lock_irq(&current->pi_lock);
  3037. raw_spin_unlock_irq(&current->pi_lock);
  3038. /* Causes final put_task_struct in finish_task_switch(): */
  3039. __set_current_state(TASK_DEAD);
  3040. /* Tell freezer to ignore us: */
  3041. current->flags |= PF_NOFREEZE;
  3042. __schedule(false);
  3043. BUG();
  3044. /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
  3045. for (;;)
  3046. cpu_relax();
  3047. }
  3048. static inline void sched_submit_work(struct task_struct *tsk)
  3049. {
  3050. if (!tsk->state || tsk_is_pi_blocked(tsk))
  3051. return;
  3052. /*
  3053. * If we are going to sleep and we have plugged IO queued,
  3054. * make sure to submit it to avoid deadlocks.
  3055. */
  3056. if (blk_needs_flush_plug(tsk))
  3057. blk_schedule_flush_plug(tsk);
  3058. }
  3059. asmlinkage __visible void __sched schedule(void)
  3060. {
  3061. struct task_struct *tsk = current;
  3062. sched_submit_work(tsk);
  3063. do {
  3064. preempt_disable();
  3065. __schedule(false);
  3066. sched_preempt_enable_no_resched();
  3067. } while (need_resched());
  3068. }
  3069. EXPORT_SYMBOL(schedule);
  3070. /*
  3071. * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
  3072. * state (have scheduled out non-voluntarily) by making sure that all
  3073. * tasks have either left the run queue or have gone into user space.
  3074. * As idle tasks do not do either, they must not ever be preempted
  3075. * (schedule out non-voluntarily).
  3076. *
  3077. * schedule_idle() is similar to schedule_preempt_disable() except that it
  3078. * never enables preemption because it does not call sched_submit_work().
  3079. */
  3080. void __sched schedule_idle(void)
  3081. {
  3082. /*
  3083. * As this skips calling sched_submit_work(), which the idle task does
  3084. * regardless because that function is a nop when the task is in a
  3085. * TASK_RUNNING state, make sure this isn't used someplace that the
  3086. * current task can be in any other state. Note, idle is always in the
  3087. * TASK_RUNNING state.
  3088. */
  3089. WARN_ON_ONCE(current->state);
  3090. do {
  3091. __schedule(false);
  3092. } while (need_resched());
  3093. }
  3094. #ifdef CONFIG_CONTEXT_TRACKING
  3095. asmlinkage __visible void __sched schedule_user(void)
  3096. {
  3097. /*
  3098. * If we come here after a random call to set_need_resched(),
  3099. * or we have been woken up remotely but the IPI has not yet arrived,
  3100. * we haven't yet exited the RCU idle mode. Do it here manually until
  3101. * we find a better solution.
  3102. *
  3103. * NB: There are buggy callers of this function. Ideally we
  3104. * should warn if prev_state != CONTEXT_USER, but that will trigger
  3105. * too frequently to make sense yet.
  3106. */
  3107. enum ctx_state prev_state = exception_enter();
  3108. schedule();
  3109. exception_exit(prev_state);
  3110. }
  3111. #endif
  3112. /**
  3113. * schedule_preempt_disabled - called with preemption disabled
  3114. *
  3115. * Returns with preemption disabled. Note: preempt_count must be 1
  3116. */
  3117. void __sched schedule_preempt_disabled(void)
  3118. {
  3119. sched_preempt_enable_no_resched();
  3120. schedule();
  3121. preempt_disable();
  3122. }
  3123. static void __sched notrace preempt_schedule_common(void)
  3124. {
  3125. do {
  3126. /*
  3127. * Because the function tracer can trace preempt_count_sub()
  3128. * and it also uses preempt_enable/disable_notrace(), if
  3129. * NEED_RESCHED is set, the preempt_enable_notrace() called
  3130. * by the function tracer will call this function again and
  3131. * cause infinite recursion.
  3132. *
  3133. * Preemption must be disabled here before the function
  3134. * tracer can trace. Break up preempt_disable() into two
  3135. * calls. One to disable preemption without fear of being
  3136. * traced. The other to still record the preemption latency,
  3137. * which can also be traced by the function tracer.
  3138. */
  3139. preempt_disable_notrace();
  3140. preempt_latency_start(1);
  3141. __schedule(true);
  3142. preempt_latency_stop(1);
  3143. preempt_enable_no_resched_notrace();
  3144. /*
  3145. * Check again in case we missed a preemption opportunity
  3146. * between schedule and now.
  3147. */
  3148. } while (need_resched());
  3149. }
  3150. #ifdef CONFIG_PREEMPT
  3151. /*
  3152. * this is the entry point to schedule() from in-kernel preemption
  3153. * off of preempt_enable. Kernel preemptions off return from interrupt
  3154. * occur there and call schedule directly.
  3155. */
  3156. asmlinkage __visible void __sched notrace preempt_schedule(void)
  3157. {
  3158. /*
  3159. * If there is a non-zero preempt_count or interrupts are disabled,
  3160. * we do not want to preempt the current task. Just return..
  3161. */
  3162. if (likely(!preemptible()))
  3163. return;
  3164. preempt_schedule_common();
  3165. }
  3166. NOKPROBE_SYMBOL(preempt_schedule);
  3167. EXPORT_SYMBOL(preempt_schedule);
  3168. /**
  3169. * preempt_schedule_notrace - preempt_schedule called by tracing
  3170. *
  3171. * The tracing infrastructure uses preempt_enable_notrace to prevent
  3172. * recursion and tracing preempt enabling caused by the tracing
  3173. * infrastructure itself. But as tracing can happen in areas coming
  3174. * from userspace or just about to enter userspace, a preempt enable
  3175. * can occur before user_exit() is called. This will cause the scheduler
  3176. * to be called when the system is still in usermode.
  3177. *
  3178. * To prevent this, the preempt_enable_notrace will use this function
  3179. * instead of preempt_schedule() to exit user context if needed before
  3180. * calling the scheduler.
  3181. */
  3182. asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
  3183. {
  3184. enum ctx_state prev_ctx;
  3185. if (likely(!preemptible()))
  3186. return;
  3187. do {
  3188. /*
  3189. * Because the function tracer can trace preempt_count_sub()
  3190. * and it also uses preempt_enable/disable_notrace(), if
  3191. * NEED_RESCHED is set, the preempt_enable_notrace() called
  3192. * by the function tracer will call this function again and
  3193. * cause infinite recursion.
  3194. *
  3195. * Preemption must be disabled here before the function
  3196. * tracer can trace. Break up preempt_disable() into two
  3197. * calls. One to disable preemption without fear of being
  3198. * traced. The other to still record the preemption latency,
  3199. * which can also be traced by the function tracer.
  3200. */
  3201. preempt_disable_notrace();
  3202. preempt_latency_start(1);
  3203. /*
  3204. * Needs preempt disabled in case user_exit() is traced
  3205. * and the tracer calls preempt_enable_notrace() causing
  3206. * an infinite recursion.
  3207. */
  3208. prev_ctx = exception_enter();
  3209. __schedule(true);
  3210. exception_exit(prev_ctx);
  3211. preempt_latency_stop(1);
  3212. preempt_enable_no_resched_notrace();
  3213. } while (need_resched());
  3214. }
  3215. EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
  3216. #endif /* CONFIG_PREEMPT */
  3217. /*
  3218. * this is the entry point to schedule() from kernel preemption
  3219. * off of irq context.
  3220. * Note, that this is called and return with irqs disabled. This will
  3221. * protect us against recursive calling from irq.
  3222. */
  3223. asmlinkage __visible void __sched preempt_schedule_irq(void)
  3224. {
  3225. enum ctx_state prev_state;
  3226. /* Catch callers which need to be fixed */
  3227. BUG_ON(preempt_count() || !irqs_disabled());
  3228. prev_state = exception_enter();
  3229. do {
  3230. preempt_disable();
  3231. local_irq_enable();
  3232. __schedule(true);
  3233. local_irq_disable();
  3234. sched_preempt_enable_no_resched();
  3235. } while (need_resched());
  3236. exception_exit(prev_state);
  3237. }
  3238. int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
  3239. void *key)
  3240. {
  3241. return try_to_wake_up(curr->private, mode, wake_flags);
  3242. }
  3243. EXPORT_SYMBOL(default_wake_function);
  3244. #ifdef CONFIG_RT_MUTEXES
  3245. static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
  3246. {
  3247. if (pi_task)
  3248. prio = min(prio, pi_task->prio);
  3249. return prio;
  3250. }
  3251. static inline int rt_effective_prio(struct task_struct *p, int prio)
  3252. {
  3253. struct task_struct *pi_task = rt_mutex_get_top_task(p);
  3254. return __rt_effective_prio(pi_task, prio);
  3255. }
  3256. /*
  3257. * rt_mutex_setprio - set the current priority of a task
  3258. * @p: task to boost
  3259. * @pi_task: donor task
  3260. *
  3261. * This function changes the 'effective' priority of a task. It does
  3262. * not touch ->normal_prio like __setscheduler().
  3263. *
  3264. * Used by the rt_mutex code to implement priority inheritance
  3265. * logic. Call site only calls if the priority of the task changed.
  3266. */
  3267. void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
  3268. {
  3269. int prio, oldprio, queued, running, queue_flag =
  3270. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  3271. const struct sched_class *prev_class;
  3272. struct rq_flags rf;
  3273. struct rq *rq;
  3274. /* XXX used to be waiter->prio, not waiter->task->prio */
  3275. prio = __rt_effective_prio(pi_task, p->normal_prio);
  3276. /*
  3277. * If nothing changed; bail early.
  3278. */
  3279. if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
  3280. return;
  3281. rq = __task_rq_lock(p, &rf);
  3282. update_rq_clock(rq);
  3283. /*
  3284. * Set under pi_lock && rq->lock, such that the value can be used under
  3285. * either lock.
  3286. *
  3287. * Note that there is loads of tricky to make this pointer cache work
  3288. * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
  3289. * ensure a task is de-boosted (pi_task is set to NULL) before the
  3290. * task is allowed to run again (and can exit). This ensures the pointer
  3291. * points to a blocked task -- which guaratees the task is present.
  3292. */
  3293. p->pi_top_task = pi_task;
  3294. /*
  3295. * For FIFO/RR we only need to set prio, if that matches we're done.
  3296. */
  3297. if (prio == p->prio && !dl_prio(prio))
  3298. goto out_unlock;
  3299. /*
  3300. * Idle task boosting is a nono in general. There is one
  3301. * exception, when PREEMPT_RT and NOHZ is active:
  3302. *
  3303. * The idle task calls get_next_timer_interrupt() and holds
  3304. * the timer wheel base->lock on the CPU and another CPU wants
  3305. * to access the timer (probably to cancel it). We can safely
  3306. * ignore the boosting request, as the idle CPU runs this code
  3307. * with interrupts disabled and will complete the lock
  3308. * protected section without being interrupted. So there is no
  3309. * real need to boost.
  3310. */
  3311. if (unlikely(p == rq->idle)) {
  3312. WARN_ON(p != rq->curr);
  3313. WARN_ON(p->pi_blocked_on);
  3314. goto out_unlock;
  3315. }
  3316. trace_sched_pi_setprio(p, pi_task);
  3317. oldprio = p->prio;
  3318. if (oldprio == prio)
  3319. queue_flag &= ~DEQUEUE_MOVE;
  3320. prev_class = p->sched_class;
  3321. queued = task_on_rq_queued(p);
  3322. running = task_current(rq, p);
  3323. if (queued)
  3324. dequeue_task(rq, p, queue_flag);
  3325. if (running)
  3326. put_prev_task(rq, p);
  3327. /*
  3328. * Boosting condition are:
  3329. * 1. -rt task is running and holds mutex A
  3330. * --> -dl task blocks on mutex A
  3331. *
  3332. * 2. -dl task is running and holds mutex A
  3333. * --> -dl task blocks on mutex A and could preempt the
  3334. * running task
  3335. */
  3336. if (dl_prio(prio)) {
  3337. if (!dl_prio(p->normal_prio) ||
  3338. (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
  3339. p->dl.dl_boosted = 1;
  3340. queue_flag |= ENQUEUE_REPLENISH;
  3341. } else
  3342. p->dl.dl_boosted = 0;
  3343. p->sched_class = &dl_sched_class;
  3344. } else if (rt_prio(prio)) {
  3345. if (dl_prio(oldprio))
  3346. p->dl.dl_boosted = 0;
  3347. if (oldprio < prio)
  3348. queue_flag |= ENQUEUE_HEAD;
  3349. p->sched_class = &rt_sched_class;
  3350. } else {
  3351. if (dl_prio(oldprio))
  3352. p->dl.dl_boosted = 0;
  3353. if (rt_prio(oldprio))
  3354. p->rt.timeout = 0;
  3355. p->sched_class = &fair_sched_class;
  3356. }
  3357. p->prio = prio;
  3358. if (queued)
  3359. enqueue_task(rq, p, queue_flag);
  3360. if (running)
  3361. set_curr_task(rq, p);
  3362. check_class_changed(rq, p, prev_class, oldprio);
  3363. out_unlock:
  3364. /* Avoid rq from going away on us: */
  3365. preempt_disable();
  3366. __task_rq_unlock(rq, &rf);
  3367. balance_callback(rq);
  3368. preempt_enable();
  3369. }
  3370. #else
  3371. static inline int rt_effective_prio(struct task_struct *p, int prio)
  3372. {
  3373. return prio;
  3374. }
  3375. #endif
  3376. void set_user_nice(struct task_struct *p, long nice)
  3377. {
  3378. bool queued, running;
  3379. int old_prio, delta;
  3380. struct rq_flags rf;
  3381. struct rq *rq;
  3382. if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
  3383. return;
  3384. /*
  3385. * We have to be careful, if called from sys_setpriority(),
  3386. * the task might be in the middle of scheduling on another CPU.
  3387. */
  3388. rq = task_rq_lock(p, &rf);
  3389. update_rq_clock(rq);
  3390. /*
  3391. * The RT priorities are set via sched_setscheduler(), but we still
  3392. * allow the 'normal' nice value to be set - but as expected
  3393. * it wont have any effect on scheduling until the task is
  3394. * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
  3395. */
  3396. if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
  3397. p->static_prio = NICE_TO_PRIO(nice);
  3398. goto out_unlock;
  3399. }
  3400. queued = task_on_rq_queued(p);
  3401. running = task_current(rq, p);
  3402. if (queued)
  3403. dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
  3404. if (running)
  3405. put_prev_task(rq, p);
  3406. p->static_prio = NICE_TO_PRIO(nice);
  3407. set_load_weight(p, true);
  3408. old_prio = p->prio;
  3409. p->prio = effective_prio(p);
  3410. delta = p->prio - old_prio;
  3411. if (queued) {
  3412. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  3413. /*
  3414. * If the task increased its priority or is running and
  3415. * lowered its priority, then reschedule its CPU:
  3416. */
  3417. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  3418. resched_curr(rq);
  3419. }
  3420. if (running)
  3421. set_curr_task(rq, p);
  3422. out_unlock:
  3423. task_rq_unlock(rq, p, &rf);
  3424. }
  3425. EXPORT_SYMBOL(set_user_nice);
  3426. /*
  3427. * can_nice - check if a task can reduce its nice value
  3428. * @p: task
  3429. * @nice: nice value
  3430. */
  3431. int can_nice(const struct task_struct *p, const int nice)
  3432. {
  3433. /* Convert nice value [19,-20] to rlimit style value [1,40]: */
  3434. int nice_rlim = nice_to_rlimit(nice);
  3435. return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
  3436. capable(CAP_SYS_NICE));
  3437. }
  3438. #ifdef __ARCH_WANT_SYS_NICE
  3439. /*
  3440. * sys_nice - change the priority of the current process.
  3441. * @increment: priority increment
  3442. *
  3443. * sys_setpriority is a more generic, but much slower function that
  3444. * does similar things.
  3445. */
  3446. SYSCALL_DEFINE1(nice, int, increment)
  3447. {
  3448. long nice, retval;
  3449. /*
  3450. * Setpriority might change our priority at the same moment.
  3451. * We don't have to worry. Conceptually one call occurs first
  3452. * and we have a single winner.
  3453. */
  3454. increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
  3455. nice = task_nice(current) + increment;
  3456. nice = clamp_val(nice, MIN_NICE, MAX_NICE);
  3457. if (increment < 0 && !can_nice(current, nice))
  3458. return -EPERM;
  3459. retval = security_task_setnice(current, nice);
  3460. if (retval)
  3461. return retval;
  3462. set_user_nice(current, nice);
  3463. return 0;
  3464. }
  3465. #endif
  3466. /**
  3467. * task_prio - return the priority value of a given task.
  3468. * @p: the task in question.
  3469. *
  3470. * Return: The priority value as seen by users in /proc.
  3471. * RT tasks are offset by -200. Normal tasks are centered
  3472. * around 0, value goes from -16 to +15.
  3473. */
  3474. int task_prio(const struct task_struct *p)
  3475. {
  3476. return p->prio - MAX_RT_PRIO;
  3477. }
  3478. /**
  3479. * idle_cpu - is a given CPU idle currently?
  3480. * @cpu: the processor in question.
  3481. *
  3482. * Return: 1 if the CPU is currently idle. 0 otherwise.
  3483. */
  3484. int idle_cpu(int cpu)
  3485. {
  3486. struct rq *rq = cpu_rq(cpu);
  3487. if (rq->curr != rq->idle)
  3488. return 0;
  3489. if (rq->nr_running)
  3490. return 0;
  3491. #ifdef CONFIG_SMP
  3492. if (!llist_empty(&rq->wake_list))
  3493. return 0;
  3494. #endif
  3495. return 1;
  3496. }
  3497. /**
  3498. * idle_task - return the idle task for a given CPU.
  3499. * @cpu: the processor in question.
  3500. *
  3501. * Return: The idle task for the CPU @cpu.
  3502. */
  3503. struct task_struct *idle_task(int cpu)
  3504. {
  3505. return cpu_rq(cpu)->idle;
  3506. }
  3507. /**
  3508. * find_process_by_pid - find a process with a matching PID value.
  3509. * @pid: the pid in question.
  3510. *
  3511. * The task of @pid, if found. %NULL otherwise.
  3512. */
  3513. static struct task_struct *find_process_by_pid(pid_t pid)
  3514. {
  3515. return pid ? find_task_by_vpid(pid) : current;
  3516. }
  3517. /*
  3518. * sched_setparam() passes in -1 for its policy, to let the functions
  3519. * it calls know not to change it.
  3520. */
  3521. #define SETPARAM_POLICY -1
  3522. static void __setscheduler_params(struct task_struct *p,
  3523. const struct sched_attr *attr)
  3524. {
  3525. int policy = attr->sched_policy;
  3526. if (policy == SETPARAM_POLICY)
  3527. policy = p->policy;
  3528. p->policy = policy;
  3529. if (dl_policy(policy))
  3530. __setparam_dl(p, attr);
  3531. else if (fair_policy(policy))
  3532. p->static_prio = NICE_TO_PRIO(attr->sched_nice);
  3533. /*
  3534. * __sched_setscheduler() ensures attr->sched_priority == 0 when
  3535. * !rt_policy. Always setting this ensures that things like
  3536. * getparam()/getattr() don't report silly values for !rt tasks.
  3537. */
  3538. p->rt_priority = attr->sched_priority;
  3539. p->normal_prio = normal_prio(p);
  3540. set_load_weight(p, true);
  3541. }
  3542. /* Actually do priority change: must hold pi & rq lock. */
  3543. static void __setscheduler(struct rq *rq, struct task_struct *p,
  3544. const struct sched_attr *attr, bool keep_boost)
  3545. {
  3546. __setscheduler_params(p, attr);
  3547. /*
  3548. * Keep a potential priority boosting if called from
  3549. * sched_setscheduler().
  3550. */
  3551. p->prio = normal_prio(p);
  3552. if (keep_boost)
  3553. p->prio = rt_effective_prio(p, p->prio);
  3554. if (dl_prio(p->prio))
  3555. p->sched_class = &dl_sched_class;
  3556. else if (rt_prio(p->prio))
  3557. p->sched_class = &rt_sched_class;
  3558. else
  3559. p->sched_class = &fair_sched_class;
  3560. }
  3561. /*
  3562. * Check the target process has a UID that matches the current process's:
  3563. */
  3564. static bool check_same_owner(struct task_struct *p)
  3565. {
  3566. const struct cred *cred = current_cred(), *pcred;
  3567. bool match;
  3568. rcu_read_lock();
  3569. pcred = __task_cred(p);
  3570. match = (uid_eq(cred->euid, pcred->euid) ||
  3571. uid_eq(cred->euid, pcred->uid));
  3572. rcu_read_unlock();
  3573. return match;
  3574. }
  3575. static int __sched_setscheduler(struct task_struct *p,
  3576. const struct sched_attr *attr,
  3577. bool user, bool pi)
  3578. {
  3579. int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
  3580. MAX_RT_PRIO - 1 - attr->sched_priority;
  3581. int retval, oldprio, oldpolicy = -1, queued, running;
  3582. int new_effective_prio, policy = attr->sched_policy;
  3583. const struct sched_class *prev_class;
  3584. struct rq_flags rf;
  3585. int reset_on_fork;
  3586. int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  3587. struct rq *rq;
  3588. /* The pi code expects interrupts enabled */
  3589. BUG_ON(pi && in_interrupt());
  3590. recheck:
  3591. /* Double check policy once rq lock held: */
  3592. if (policy < 0) {
  3593. reset_on_fork = p->sched_reset_on_fork;
  3594. policy = oldpolicy = p->policy;
  3595. } else {
  3596. reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
  3597. if (!valid_policy(policy))
  3598. return -EINVAL;
  3599. }
  3600. if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
  3601. return -EINVAL;
  3602. /*
  3603. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3604. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
  3605. * SCHED_BATCH and SCHED_IDLE is 0.
  3606. */
  3607. if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
  3608. (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
  3609. return -EINVAL;
  3610. if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
  3611. (rt_policy(policy) != (attr->sched_priority != 0)))
  3612. return -EINVAL;
  3613. /*
  3614. * Allow unprivileged RT tasks to decrease priority:
  3615. */
  3616. if (user && !capable(CAP_SYS_NICE)) {
  3617. if (fair_policy(policy)) {
  3618. if (attr->sched_nice < task_nice(p) &&
  3619. !can_nice(p, attr->sched_nice))
  3620. return -EPERM;
  3621. }
  3622. if (rt_policy(policy)) {
  3623. unsigned long rlim_rtprio =
  3624. task_rlimit(p, RLIMIT_RTPRIO);
  3625. /* Can't set/change the rt policy: */
  3626. if (policy != p->policy && !rlim_rtprio)
  3627. return -EPERM;
  3628. /* Can't increase priority: */
  3629. if (attr->sched_priority > p->rt_priority &&
  3630. attr->sched_priority > rlim_rtprio)
  3631. return -EPERM;
  3632. }
  3633. /*
  3634. * Can't set/change SCHED_DEADLINE policy at all for now
  3635. * (safest behavior); in the future we would like to allow
  3636. * unprivileged DL tasks to increase their relative deadline
  3637. * or reduce their runtime (both ways reducing utilization)
  3638. */
  3639. if (dl_policy(policy))
  3640. return -EPERM;
  3641. /*
  3642. * Treat SCHED_IDLE as nice 20. Only allow a switch to
  3643. * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
  3644. */
  3645. if (idle_policy(p->policy) && !idle_policy(policy)) {
  3646. if (!can_nice(p, task_nice(p)))
  3647. return -EPERM;
  3648. }
  3649. /* Can't change other user's priorities: */
  3650. if (!check_same_owner(p))
  3651. return -EPERM;
  3652. /* Normal users shall not reset the sched_reset_on_fork flag: */
  3653. if (p->sched_reset_on_fork && !reset_on_fork)
  3654. return -EPERM;
  3655. }
  3656. if (user) {
  3657. if (attr->sched_flags & SCHED_FLAG_SUGOV)
  3658. return -EINVAL;
  3659. retval = security_task_setscheduler(p);
  3660. if (retval)
  3661. return retval;
  3662. }
  3663. /*
  3664. * Make sure no PI-waiters arrive (or leave) while we are
  3665. * changing the priority of the task:
  3666. *
  3667. * To be able to change p->policy safely, the appropriate
  3668. * runqueue lock must be held.
  3669. */
  3670. rq = task_rq_lock(p, &rf);
  3671. update_rq_clock(rq);
  3672. /*
  3673. * Changing the policy of the stop threads its a very bad idea:
  3674. */
  3675. if (p == rq->stop) {
  3676. task_rq_unlock(rq, p, &rf);
  3677. return -EINVAL;
  3678. }
  3679. /*
  3680. * If not changing anything there's no need to proceed further,
  3681. * but store a possible modification of reset_on_fork.
  3682. */
  3683. if (unlikely(policy == p->policy)) {
  3684. if (fair_policy(policy) && attr->sched_nice != task_nice(p))
  3685. goto change;
  3686. if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
  3687. goto change;
  3688. if (dl_policy(policy) && dl_param_changed(p, attr))
  3689. goto change;
  3690. p->sched_reset_on_fork = reset_on_fork;
  3691. task_rq_unlock(rq, p, &rf);
  3692. return 0;
  3693. }
  3694. change:
  3695. if (user) {
  3696. #ifdef CONFIG_RT_GROUP_SCHED
  3697. /*
  3698. * Do not allow realtime tasks into groups that have no runtime
  3699. * assigned.
  3700. */
  3701. if (rt_bandwidth_enabled() && rt_policy(policy) &&
  3702. task_group(p)->rt_bandwidth.rt_runtime == 0 &&
  3703. !task_group_is_autogroup(task_group(p))) {
  3704. task_rq_unlock(rq, p, &rf);
  3705. return -EPERM;
  3706. }
  3707. #endif
  3708. #ifdef CONFIG_SMP
  3709. if (dl_bandwidth_enabled() && dl_policy(policy) &&
  3710. !(attr->sched_flags & SCHED_FLAG_SUGOV)) {
  3711. cpumask_t *span = rq->rd->span;
  3712. /*
  3713. * Don't allow tasks with an affinity mask smaller than
  3714. * the entire root_domain to become SCHED_DEADLINE. We
  3715. * will also fail if there's no bandwidth available.
  3716. */
  3717. if (!cpumask_subset(span, &p->cpus_allowed) ||
  3718. rq->rd->dl_bw.bw == 0) {
  3719. task_rq_unlock(rq, p, &rf);
  3720. return -EPERM;
  3721. }
  3722. }
  3723. #endif
  3724. }
  3725. /* Re-check policy now with rq lock held: */
  3726. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3727. policy = oldpolicy = -1;
  3728. task_rq_unlock(rq, p, &rf);
  3729. goto recheck;
  3730. }
  3731. /*
  3732. * If setscheduling to SCHED_DEADLINE (or changing the parameters
  3733. * of a SCHED_DEADLINE task) we need to check if enough bandwidth
  3734. * is available.
  3735. */
  3736. if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
  3737. task_rq_unlock(rq, p, &rf);
  3738. return -EBUSY;
  3739. }
  3740. p->sched_reset_on_fork = reset_on_fork;
  3741. oldprio = p->prio;
  3742. if (pi) {
  3743. /*
  3744. * Take priority boosted tasks into account. If the new
  3745. * effective priority is unchanged, we just store the new
  3746. * normal parameters and do not touch the scheduler class and
  3747. * the runqueue. This will be done when the task deboost
  3748. * itself.
  3749. */
  3750. new_effective_prio = rt_effective_prio(p, newprio);
  3751. if (new_effective_prio == oldprio)
  3752. queue_flags &= ~DEQUEUE_MOVE;
  3753. }
  3754. queued = task_on_rq_queued(p);
  3755. running = task_current(rq, p);
  3756. if (queued)
  3757. dequeue_task(rq, p, queue_flags);
  3758. if (running)
  3759. put_prev_task(rq, p);
  3760. prev_class = p->sched_class;
  3761. __setscheduler(rq, p, attr, pi);
  3762. if (queued) {
  3763. /*
  3764. * We enqueue to tail when the priority of a task is
  3765. * increased (user space view).
  3766. */
  3767. if (oldprio < p->prio)
  3768. queue_flags |= ENQUEUE_HEAD;
  3769. enqueue_task(rq, p, queue_flags);
  3770. }
  3771. if (running)
  3772. set_curr_task(rq, p);
  3773. check_class_changed(rq, p, prev_class, oldprio);
  3774. /* Avoid rq from going away on us: */
  3775. preempt_disable();
  3776. task_rq_unlock(rq, p, &rf);
  3777. if (pi)
  3778. rt_mutex_adjust_pi(p);
  3779. /* Run balance callbacks after we've adjusted the PI chain: */
  3780. balance_callback(rq);
  3781. preempt_enable();
  3782. return 0;
  3783. }
  3784. static int _sched_setscheduler(struct task_struct *p, int policy,
  3785. const struct sched_param *param, bool check)
  3786. {
  3787. struct sched_attr attr = {
  3788. .sched_policy = policy,
  3789. .sched_priority = param->sched_priority,
  3790. .sched_nice = PRIO_TO_NICE(p->static_prio),
  3791. };
  3792. /* Fixup the legacy SCHED_RESET_ON_FORK hack. */
  3793. if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
  3794. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  3795. policy &= ~SCHED_RESET_ON_FORK;
  3796. attr.sched_policy = policy;
  3797. }
  3798. return __sched_setscheduler(p, &attr, check, true);
  3799. }
  3800. /**
  3801. * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
  3802. * @p: the task in question.
  3803. * @policy: new policy.
  3804. * @param: structure containing the new RT priority.
  3805. *
  3806. * Return: 0 on success. An error code otherwise.
  3807. *
  3808. * NOTE that the task may be already dead.
  3809. */
  3810. int sched_setscheduler(struct task_struct *p, int policy,
  3811. const struct sched_param *param)
  3812. {
  3813. return _sched_setscheduler(p, policy, param, true);
  3814. }
  3815. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3816. int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
  3817. {
  3818. return __sched_setscheduler(p, attr, true, true);
  3819. }
  3820. EXPORT_SYMBOL_GPL(sched_setattr);
  3821. int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
  3822. {
  3823. return __sched_setscheduler(p, attr, false, true);
  3824. }
  3825. /**
  3826. * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
  3827. * @p: the task in question.
  3828. * @policy: new policy.
  3829. * @param: structure containing the new RT priority.
  3830. *
  3831. * Just like sched_setscheduler, only don't bother checking if the
  3832. * current context has permission. For example, this is needed in
  3833. * stop_machine(): we create temporary high priority worker threads,
  3834. * but our caller might not have that capability.
  3835. *
  3836. * Return: 0 on success. An error code otherwise.
  3837. */
  3838. int sched_setscheduler_nocheck(struct task_struct *p, int policy,
  3839. const struct sched_param *param)
  3840. {
  3841. return _sched_setscheduler(p, policy, param, false);
  3842. }
  3843. EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
  3844. static int
  3845. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3846. {
  3847. struct sched_param lparam;
  3848. struct task_struct *p;
  3849. int retval;
  3850. if (!param || pid < 0)
  3851. return -EINVAL;
  3852. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3853. return -EFAULT;
  3854. rcu_read_lock();
  3855. retval = -ESRCH;
  3856. p = find_process_by_pid(pid);
  3857. if (p != NULL)
  3858. retval = sched_setscheduler(p, policy, &lparam);
  3859. rcu_read_unlock();
  3860. return retval;
  3861. }
  3862. /*
  3863. * Mimics kernel/events/core.c perf_copy_attr().
  3864. */
  3865. static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
  3866. {
  3867. u32 size;
  3868. int ret;
  3869. if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
  3870. return -EFAULT;
  3871. /* Zero the full structure, so that a short copy will be nice: */
  3872. memset(attr, 0, sizeof(*attr));
  3873. ret = get_user(size, &uattr->size);
  3874. if (ret)
  3875. return ret;
  3876. /* Bail out on silly large: */
  3877. if (size > PAGE_SIZE)
  3878. goto err_size;
  3879. /* ABI compatibility quirk: */
  3880. if (!size)
  3881. size = SCHED_ATTR_SIZE_VER0;
  3882. if (size < SCHED_ATTR_SIZE_VER0)
  3883. goto err_size;
  3884. /*
  3885. * If we're handed a bigger struct than we know of,
  3886. * ensure all the unknown bits are 0 - i.e. new
  3887. * user-space does not rely on any kernel feature
  3888. * extensions we dont know about yet.
  3889. */
  3890. if (size > sizeof(*attr)) {
  3891. unsigned char __user *addr;
  3892. unsigned char __user *end;
  3893. unsigned char val;
  3894. addr = (void __user *)uattr + sizeof(*attr);
  3895. end = (void __user *)uattr + size;
  3896. for (; addr < end; addr++) {
  3897. ret = get_user(val, addr);
  3898. if (ret)
  3899. return ret;
  3900. if (val)
  3901. goto err_size;
  3902. }
  3903. size = sizeof(*attr);
  3904. }
  3905. ret = copy_from_user(attr, uattr, size);
  3906. if (ret)
  3907. return -EFAULT;
  3908. /*
  3909. * XXX: Do we want to be lenient like existing syscalls; or do we want
  3910. * to be strict and return an error on out-of-bounds values?
  3911. */
  3912. attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
  3913. return 0;
  3914. err_size:
  3915. put_user(sizeof(*attr), &uattr->size);
  3916. return -E2BIG;
  3917. }
  3918. /**
  3919. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3920. * @pid: the pid in question.
  3921. * @policy: new policy.
  3922. * @param: structure containing the new RT priority.
  3923. *
  3924. * Return: 0 on success. An error code otherwise.
  3925. */
  3926. SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
  3927. {
  3928. if (policy < 0)
  3929. return -EINVAL;
  3930. return do_sched_setscheduler(pid, policy, param);
  3931. }
  3932. /**
  3933. * sys_sched_setparam - set/change the RT priority of a thread
  3934. * @pid: the pid in question.
  3935. * @param: structure containing the new RT priority.
  3936. *
  3937. * Return: 0 on success. An error code otherwise.
  3938. */
  3939. SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
  3940. {
  3941. return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
  3942. }
  3943. /**
  3944. * sys_sched_setattr - same as above, but with extended sched_attr
  3945. * @pid: the pid in question.
  3946. * @uattr: structure containing the extended parameters.
  3947. * @flags: for future extension.
  3948. */
  3949. SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
  3950. unsigned int, flags)
  3951. {
  3952. struct sched_attr attr;
  3953. struct task_struct *p;
  3954. int retval;
  3955. if (!uattr || pid < 0 || flags)
  3956. return -EINVAL;
  3957. retval = sched_copy_attr(uattr, &attr);
  3958. if (retval)
  3959. return retval;
  3960. if ((int)attr.sched_policy < 0)
  3961. return -EINVAL;
  3962. rcu_read_lock();
  3963. retval = -ESRCH;
  3964. p = find_process_by_pid(pid);
  3965. if (p != NULL)
  3966. retval = sched_setattr(p, &attr);
  3967. rcu_read_unlock();
  3968. return retval;
  3969. }
  3970. /**
  3971. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3972. * @pid: the pid in question.
  3973. *
  3974. * Return: On success, the policy of the thread. Otherwise, a negative error
  3975. * code.
  3976. */
  3977. SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
  3978. {
  3979. struct task_struct *p;
  3980. int retval;
  3981. if (pid < 0)
  3982. return -EINVAL;
  3983. retval = -ESRCH;
  3984. rcu_read_lock();
  3985. p = find_process_by_pid(pid);
  3986. if (p) {
  3987. retval = security_task_getscheduler(p);
  3988. if (!retval)
  3989. retval = p->policy
  3990. | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
  3991. }
  3992. rcu_read_unlock();
  3993. return retval;
  3994. }
  3995. /**
  3996. * sys_sched_getparam - get the RT priority of a thread
  3997. * @pid: the pid in question.
  3998. * @param: structure containing the RT priority.
  3999. *
  4000. * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
  4001. * code.
  4002. */
  4003. SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
  4004. {
  4005. struct sched_param lp = { .sched_priority = 0 };
  4006. struct task_struct *p;
  4007. int retval;
  4008. if (!param || pid < 0)
  4009. return -EINVAL;
  4010. rcu_read_lock();
  4011. p = find_process_by_pid(pid);
  4012. retval = -ESRCH;
  4013. if (!p)
  4014. goto out_unlock;
  4015. retval = security_task_getscheduler(p);
  4016. if (retval)
  4017. goto out_unlock;
  4018. if (task_has_rt_policy(p))
  4019. lp.sched_priority = p->rt_priority;
  4020. rcu_read_unlock();
  4021. /*
  4022. * This one might sleep, we cannot do it with a spinlock held ...
  4023. */
  4024. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  4025. return retval;
  4026. out_unlock:
  4027. rcu_read_unlock();
  4028. return retval;
  4029. }
  4030. static int sched_read_attr(struct sched_attr __user *uattr,
  4031. struct sched_attr *attr,
  4032. unsigned int usize)
  4033. {
  4034. int ret;
  4035. if (!access_ok(VERIFY_WRITE, uattr, usize))
  4036. return -EFAULT;
  4037. /*
  4038. * If we're handed a smaller struct than we know of,
  4039. * ensure all the unknown bits are 0 - i.e. old
  4040. * user-space does not get uncomplete information.
  4041. */
  4042. if (usize < sizeof(*attr)) {
  4043. unsigned char *addr;
  4044. unsigned char *end;
  4045. addr = (void *)attr + usize;
  4046. end = (void *)attr + sizeof(*attr);
  4047. for (; addr < end; addr++) {
  4048. if (*addr)
  4049. return -EFBIG;
  4050. }
  4051. attr->size = usize;
  4052. }
  4053. ret = copy_to_user(uattr, attr, attr->size);
  4054. if (ret)
  4055. return -EFAULT;
  4056. return 0;
  4057. }
  4058. /**
  4059. * sys_sched_getattr - similar to sched_getparam, but with sched_attr
  4060. * @pid: the pid in question.
  4061. * @uattr: structure containing the extended parameters.
  4062. * @size: sizeof(attr) for fwd/bwd comp.
  4063. * @flags: for future extension.
  4064. */
  4065. SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
  4066. unsigned int, size, unsigned int, flags)
  4067. {
  4068. struct sched_attr attr = {
  4069. .size = sizeof(struct sched_attr),
  4070. };
  4071. struct task_struct *p;
  4072. int retval;
  4073. if (!uattr || pid < 0 || size > PAGE_SIZE ||
  4074. size < SCHED_ATTR_SIZE_VER0 || flags)
  4075. return -EINVAL;
  4076. rcu_read_lock();
  4077. p = find_process_by_pid(pid);
  4078. retval = -ESRCH;
  4079. if (!p)
  4080. goto out_unlock;
  4081. retval = security_task_getscheduler(p);
  4082. if (retval)
  4083. goto out_unlock;
  4084. attr.sched_policy = p->policy;
  4085. if (p->sched_reset_on_fork)
  4086. attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
  4087. if (task_has_dl_policy(p))
  4088. __getparam_dl(p, &attr);
  4089. else if (task_has_rt_policy(p))
  4090. attr.sched_priority = p->rt_priority;
  4091. else
  4092. attr.sched_nice = task_nice(p);
  4093. rcu_read_unlock();
  4094. retval = sched_read_attr(uattr, &attr, size);
  4095. return retval;
  4096. out_unlock:
  4097. rcu_read_unlock();
  4098. return retval;
  4099. }
  4100. long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
  4101. {
  4102. cpumask_var_t cpus_allowed, new_mask;
  4103. struct task_struct *p;
  4104. int retval;
  4105. rcu_read_lock();
  4106. p = find_process_by_pid(pid);
  4107. if (!p) {
  4108. rcu_read_unlock();
  4109. return -ESRCH;
  4110. }
  4111. /* Prevent p going away */
  4112. get_task_struct(p);
  4113. rcu_read_unlock();
  4114. if (p->flags & PF_NO_SETAFFINITY) {
  4115. retval = -EINVAL;
  4116. goto out_put_task;
  4117. }
  4118. if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
  4119. retval = -ENOMEM;
  4120. goto out_put_task;
  4121. }
  4122. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
  4123. retval = -ENOMEM;
  4124. goto out_free_cpus_allowed;
  4125. }
  4126. retval = -EPERM;
  4127. if (!check_same_owner(p)) {
  4128. rcu_read_lock();
  4129. if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
  4130. rcu_read_unlock();
  4131. goto out_free_new_mask;
  4132. }
  4133. rcu_read_unlock();
  4134. }
  4135. retval = security_task_setscheduler(p);
  4136. if (retval)
  4137. goto out_free_new_mask;
  4138. cpuset_cpus_allowed(p, cpus_allowed);
  4139. cpumask_and(new_mask, in_mask, cpus_allowed);
  4140. /*
  4141. * Since bandwidth control happens on root_domain basis,
  4142. * if admission test is enabled, we only admit -deadline
  4143. * tasks allowed to run on all the CPUs in the task's
  4144. * root_domain.
  4145. */
  4146. #ifdef CONFIG_SMP
  4147. if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
  4148. rcu_read_lock();
  4149. if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
  4150. retval = -EBUSY;
  4151. rcu_read_unlock();
  4152. goto out_free_new_mask;
  4153. }
  4154. rcu_read_unlock();
  4155. }
  4156. #endif
  4157. again:
  4158. retval = __set_cpus_allowed_ptr(p, new_mask, true);
  4159. if (!retval) {
  4160. cpuset_cpus_allowed(p, cpus_allowed);
  4161. if (!cpumask_subset(new_mask, cpus_allowed)) {
  4162. /*
  4163. * We must have raced with a concurrent cpuset
  4164. * update. Just reset the cpus_allowed to the
  4165. * cpuset's cpus_allowed
  4166. */
  4167. cpumask_copy(new_mask, cpus_allowed);
  4168. goto again;
  4169. }
  4170. }
  4171. out_free_new_mask:
  4172. free_cpumask_var(new_mask);
  4173. out_free_cpus_allowed:
  4174. free_cpumask_var(cpus_allowed);
  4175. out_put_task:
  4176. put_task_struct(p);
  4177. return retval;
  4178. }
  4179. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  4180. struct cpumask *new_mask)
  4181. {
  4182. if (len < cpumask_size())
  4183. cpumask_clear(new_mask);
  4184. else if (len > cpumask_size())
  4185. len = cpumask_size();
  4186. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  4187. }
  4188. /**
  4189. * sys_sched_setaffinity - set the CPU affinity of a process
  4190. * @pid: pid of the process
  4191. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  4192. * @user_mask_ptr: user-space pointer to the new CPU mask
  4193. *
  4194. * Return: 0 on success. An error code otherwise.
  4195. */
  4196. SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
  4197. unsigned long __user *, user_mask_ptr)
  4198. {
  4199. cpumask_var_t new_mask;
  4200. int retval;
  4201. if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
  4202. return -ENOMEM;
  4203. retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
  4204. if (retval == 0)
  4205. retval = sched_setaffinity(pid, new_mask);
  4206. free_cpumask_var(new_mask);
  4207. return retval;
  4208. }
  4209. long sched_getaffinity(pid_t pid, struct cpumask *mask)
  4210. {
  4211. struct task_struct *p;
  4212. unsigned long flags;
  4213. int retval;
  4214. rcu_read_lock();
  4215. retval = -ESRCH;
  4216. p = find_process_by_pid(pid);
  4217. if (!p)
  4218. goto out_unlock;
  4219. retval = security_task_getscheduler(p);
  4220. if (retval)
  4221. goto out_unlock;
  4222. raw_spin_lock_irqsave(&p->pi_lock, flags);
  4223. cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
  4224. raw_spin_unlock_irqrestore(&p->pi_lock, flags);
  4225. out_unlock:
  4226. rcu_read_unlock();
  4227. return retval;
  4228. }
  4229. /**
  4230. * sys_sched_getaffinity - get the CPU affinity of a process
  4231. * @pid: pid of the process
  4232. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  4233. * @user_mask_ptr: user-space pointer to hold the current CPU mask
  4234. *
  4235. * Return: size of CPU mask copied to user_mask_ptr on success. An
  4236. * error code otherwise.
  4237. */
  4238. SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
  4239. unsigned long __user *, user_mask_ptr)
  4240. {
  4241. int ret;
  4242. cpumask_var_t mask;
  4243. if ((len * BITS_PER_BYTE) < nr_cpu_ids)
  4244. return -EINVAL;
  4245. if (len & (sizeof(unsigned long)-1))
  4246. return -EINVAL;
  4247. if (!alloc_cpumask_var(&mask, GFP_KERNEL))
  4248. return -ENOMEM;
  4249. ret = sched_getaffinity(pid, mask);
  4250. if (ret == 0) {
  4251. unsigned int retlen = min(len, cpumask_size());
  4252. if (copy_to_user(user_mask_ptr, mask, retlen))
  4253. ret = -EFAULT;
  4254. else
  4255. ret = retlen;
  4256. }
  4257. free_cpumask_var(mask);
  4258. return ret;
  4259. }
  4260. /**
  4261. * sys_sched_yield - yield the current processor to other threads.
  4262. *
  4263. * This function yields the current CPU to other tasks. If there are no
  4264. * other threads running on this CPU then this function will return.
  4265. *
  4266. * Return: 0.
  4267. */
  4268. SYSCALL_DEFINE0(sched_yield)
  4269. {
  4270. struct rq_flags rf;
  4271. struct rq *rq;
  4272. local_irq_disable();
  4273. rq = this_rq();
  4274. rq_lock(rq, &rf);
  4275. schedstat_inc(rq->yld_count);
  4276. current->sched_class->yield_task(rq);
  4277. /*
  4278. * Since we are going to call schedule() anyway, there's
  4279. * no need to preempt or enable interrupts:
  4280. */
  4281. preempt_disable();
  4282. rq_unlock(rq, &rf);
  4283. sched_preempt_enable_no_resched();
  4284. schedule();
  4285. return 0;
  4286. }
  4287. #ifndef CONFIG_PREEMPT
  4288. int __sched _cond_resched(void)
  4289. {
  4290. if (should_resched(0)) {
  4291. preempt_schedule_common();
  4292. return 1;
  4293. }
  4294. rcu_all_qs();
  4295. return 0;
  4296. }
  4297. EXPORT_SYMBOL(_cond_resched);
  4298. #endif
  4299. /*
  4300. * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
  4301. * call schedule, and on return reacquire the lock.
  4302. *
  4303. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  4304. * operations here to prevent schedule() from being called twice (once via
  4305. * spin_unlock(), once by hand).
  4306. */
  4307. int __cond_resched_lock(spinlock_t *lock)
  4308. {
  4309. int resched = should_resched(PREEMPT_LOCK_OFFSET);
  4310. int ret = 0;
  4311. lockdep_assert_held(lock);
  4312. if (spin_needbreak(lock) || resched) {
  4313. spin_unlock(lock);
  4314. if (resched)
  4315. preempt_schedule_common();
  4316. else
  4317. cpu_relax();
  4318. ret = 1;
  4319. spin_lock(lock);
  4320. }
  4321. return ret;
  4322. }
  4323. EXPORT_SYMBOL(__cond_resched_lock);
  4324. int __sched __cond_resched_softirq(void)
  4325. {
  4326. BUG_ON(!in_softirq());
  4327. if (should_resched(SOFTIRQ_DISABLE_OFFSET)) {
  4328. local_bh_enable();
  4329. preempt_schedule_common();
  4330. local_bh_disable();
  4331. return 1;
  4332. }
  4333. return 0;
  4334. }
  4335. EXPORT_SYMBOL(__cond_resched_softirq);
  4336. /**
  4337. * yield - yield the current processor to other threads.
  4338. *
  4339. * Do not ever use this function, there's a 99% chance you're doing it wrong.
  4340. *
  4341. * The scheduler is at all times free to pick the calling task as the most
  4342. * eligible task to run, if removing the yield() call from your code breaks
  4343. * it, its already broken.
  4344. *
  4345. * Typical broken usage is:
  4346. *
  4347. * while (!event)
  4348. * yield();
  4349. *
  4350. * where one assumes that yield() will let 'the other' process run that will
  4351. * make event true. If the current task is a SCHED_FIFO task that will never
  4352. * happen. Never use yield() as a progress guarantee!!
  4353. *
  4354. * If you want to use yield() to wait for something, use wait_event().
  4355. * If you want to use yield() to be 'nice' for others, use cond_resched().
  4356. * If you still want to use yield(), do not!
  4357. */
  4358. void __sched yield(void)
  4359. {
  4360. set_current_state(TASK_RUNNING);
  4361. sys_sched_yield();
  4362. }
  4363. EXPORT_SYMBOL(yield);
  4364. /**
  4365. * yield_to - yield the current processor to another thread in
  4366. * your thread group, or accelerate that thread toward the
  4367. * processor it's on.
  4368. * @p: target task
  4369. * @preempt: whether task preemption is allowed or not
  4370. *
  4371. * It's the caller's job to ensure that the target task struct
  4372. * can't go away on us before we can do any checks.
  4373. *
  4374. * Return:
  4375. * true (>0) if we indeed boosted the target task.
  4376. * false (0) if we failed to boost the target.
  4377. * -ESRCH if there's no task to yield to.
  4378. */
  4379. int __sched yield_to(struct task_struct *p, bool preempt)
  4380. {
  4381. struct task_struct *curr = current;
  4382. struct rq *rq, *p_rq;
  4383. unsigned long flags;
  4384. int yielded = 0;
  4385. local_irq_save(flags);
  4386. rq = this_rq();
  4387. again:
  4388. p_rq = task_rq(p);
  4389. /*
  4390. * If we're the only runnable task on the rq and target rq also
  4391. * has only one task, there's absolutely no point in yielding.
  4392. */
  4393. if (rq->nr_running == 1 && p_rq->nr_running == 1) {
  4394. yielded = -ESRCH;
  4395. goto out_irq;
  4396. }
  4397. double_rq_lock(rq, p_rq);
  4398. if (task_rq(p) != p_rq) {
  4399. double_rq_unlock(rq, p_rq);
  4400. goto again;
  4401. }
  4402. if (!curr->sched_class->yield_to_task)
  4403. goto out_unlock;
  4404. if (curr->sched_class != p->sched_class)
  4405. goto out_unlock;
  4406. if (task_running(p_rq, p) || p->state)
  4407. goto out_unlock;
  4408. yielded = curr->sched_class->yield_to_task(rq, p, preempt);
  4409. if (yielded) {
  4410. schedstat_inc(rq->yld_count);
  4411. /*
  4412. * Make p's CPU reschedule; pick_next_entity takes care of
  4413. * fairness.
  4414. */
  4415. if (preempt && rq != p_rq)
  4416. resched_curr(p_rq);
  4417. }
  4418. out_unlock:
  4419. double_rq_unlock(rq, p_rq);
  4420. out_irq:
  4421. local_irq_restore(flags);
  4422. if (yielded > 0)
  4423. schedule();
  4424. return yielded;
  4425. }
  4426. EXPORT_SYMBOL_GPL(yield_to);
  4427. int io_schedule_prepare(void)
  4428. {
  4429. int old_iowait = current->in_iowait;
  4430. current->in_iowait = 1;
  4431. blk_schedule_flush_plug(current);
  4432. return old_iowait;
  4433. }
  4434. void io_schedule_finish(int token)
  4435. {
  4436. current->in_iowait = token;
  4437. }
  4438. /*
  4439. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  4440. * that process accounting knows that this is a task in IO wait state.
  4441. */
  4442. long __sched io_schedule_timeout(long timeout)
  4443. {
  4444. int token;
  4445. long ret;
  4446. token = io_schedule_prepare();
  4447. ret = schedule_timeout(timeout);
  4448. io_schedule_finish(token);
  4449. return ret;
  4450. }
  4451. EXPORT_SYMBOL(io_schedule_timeout);
  4452. void io_schedule(void)
  4453. {
  4454. int token;
  4455. token = io_schedule_prepare();
  4456. schedule();
  4457. io_schedule_finish(token);
  4458. }
  4459. EXPORT_SYMBOL(io_schedule);
  4460. /**
  4461. * sys_sched_get_priority_max - return maximum RT priority.
  4462. * @policy: scheduling class.
  4463. *
  4464. * Return: On success, this syscall returns the maximum
  4465. * rt_priority that can be used by a given scheduling class.
  4466. * On failure, a negative error code is returned.
  4467. */
  4468. SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
  4469. {
  4470. int ret = -EINVAL;
  4471. switch (policy) {
  4472. case SCHED_FIFO:
  4473. case SCHED_RR:
  4474. ret = MAX_USER_RT_PRIO-1;
  4475. break;
  4476. case SCHED_DEADLINE:
  4477. case SCHED_NORMAL:
  4478. case SCHED_BATCH:
  4479. case SCHED_IDLE:
  4480. ret = 0;
  4481. break;
  4482. }
  4483. return ret;
  4484. }
  4485. /**
  4486. * sys_sched_get_priority_min - return minimum RT priority.
  4487. * @policy: scheduling class.
  4488. *
  4489. * Return: On success, this syscall returns the minimum
  4490. * rt_priority that can be used by a given scheduling class.
  4491. * On failure, a negative error code is returned.
  4492. */
  4493. SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
  4494. {
  4495. int ret = -EINVAL;
  4496. switch (policy) {
  4497. case SCHED_FIFO:
  4498. case SCHED_RR:
  4499. ret = 1;
  4500. break;
  4501. case SCHED_DEADLINE:
  4502. case SCHED_NORMAL:
  4503. case SCHED_BATCH:
  4504. case SCHED_IDLE:
  4505. ret = 0;
  4506. }
  4507. return ret;
  4508. }
  4509. static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
  4510. {
  4511. struct task_struct *p;
  4512. unsigned int time_slice;
  4513. struct rq_flags rf;
  4514. struct rq *rq;
  4515. int retval;
  4516. if (pid < 0)
  4517. return -EINVAL;
  4518. retval = -ESRCH;
  4519. rcu_read_lock();
  4520. p = find_process_by_pid(pid);
  4521. if (!p)
  4522. goto out_unlock;
  4523. retval = security_task_getscheduler(p);
  4524. if (retval)
  4525. goto out_unlock;
  4526. rq = task_rq_lock(p, &rf);
  4527. time_slice = 0;
  4528. if (p->sched_class->get_rr_interval)
  4529. time_slice = p->sched_class->get_rr_interval(rq, p);
  4530. task_rq_unlock(rq, p, &rf);
  4531. rcu_read_unlock();
  4532. jiffies_to_timespec64(time_slice, t);
  4533. return 0;
  4534. out_unlock:
  4535. rcu_read_unlock();
  4536. return retval;
  4537. }
  4538. /**
  4539. * sys_sched_rr_get_interval - return the default timeslice of a process.
  4540. * @pid: pid of the process.
  4541. * @interval: userspace pointer to the timeslice value.
  4542. *
  4543. * this syscall writes the default timeslice value of a given process
  4544. * into the user-space timespec buffer. A value of '0' means infinity.
  4545. *
  4546. * Return: On success, 0 and the timeslice is in @interval. Otherwise,
  4547. * an error code.
  4548. */
  4549. SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
  4550. struct timespec __user *, interval)
  4551. {
  4552. struct timespec64 t;
  4553. int retval = sched_rr_get_interval(pid, &t);
  4554. if (retval == 0)
  4555. retval = put_timespec64(&t, interval);
  4556. return retval;
  4557. }
  4558. #ifdef CONFIG_COMPAT
  4559. COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
  4560. compat_pid_t, pid,
  4561. struct compat_timespec __user *, interval)
  4562. {
  4563. struct timespec64 t;
  4564. int retval = sched_rr_get_interval(pid, &t);
  4565. if (retval == 0)
  4566. retval = compat_put_timespec64(&t, interval);
  4567. return retval;
  4568. }
  4569. #endif
  4570. void sched_show_task(struct task_struct *p)
  4571. {
  4572. unsigned long free = 0;
  4573. int ppid;
  4574. if (!try_get_task_stack(p))
  4575. return;
  4576. printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
  4577. if (p->state == TASK_RUNNING)
  4578. printk(KERN_CONT " running task ");
  4579. #ifdef CONFIG_DEBUG_STACK_USAGE
  4580. free = stack_not_used(p);
  4581. #endif
  4582. ppid = 0;
  4583. rcu_read_lock();
  4584. if (pid_alive(p))
  4585. ppid = task_pid_nr(rcu_dereference(p->real_parent));
  4586. rcu_read_unlock();
  4587. printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
  4588. task_pid_nr(p), ppid,
  4589. (unsigned long)task_thread_info(p)->flags);
  4590. print_worker_info(KERN_INFO, p);
  4591. show_stack(p, NULL);
  4592. put_task_stack(p);
  4593. }
  4594. EXPORT_SYMBOL_GPL(sched_show_task);
  4595. static inline bool
  4596. state_filter_match(unsigned long state_filter, struct task_struct *p)
  4597. {
  4598. /* no filter, everything matches */
  4599. if (!state_filter)
  4600. return true;
  4601. /* filter, but doesn't match */
  4602. if (!(p->state & state_filter))
  4603. return false;
  4604. /*
  4605. * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
  4606. * TASK_KILLABLE).
  4607. */
  4608. if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
  4609. return false;
  4610. return true;
  4611. }
  4612. void show_state_filter(unsigned long state_filter)
  4613. {
  4614. struct task_struct *g, *p;
  4615. #if BITS_PER_LONG == 32
  4616. printk(KERN_INFO
  4617. " task PC stack pid father\n");
  4618. #else
  4619. printk(KERN_INFO
  4620. " task PC stack pid father\n");
  4621. #endif
  4622. rcu_read_lock();
  4623. for_each_process_thread(g, p) {
  4624. /*
  4625. * reset the NMI-timeout, listing all files on a slow
  4626. * console might take a lot of time:
  4627. * Also, reset softlockup watchdogs on all CPUs, because
  4628. * another CPU might be blocked waiting for us to process
  4629. * an IPI.
  4630. */
  4631. touch_nmi_watchdog();
  4632. touch_all_softlockup_watchdogs();
  4633. if (state_filter_match(state_filter, p))
  4634. sched_show_task(p);
  4635. }
  4636. #ifdef CONFIG_SCHED_DEBUG
  4637. if (!state_filter)
  4638. sysrq_sched_debug_show();
  4639. #endif
  4640. rcu_read_unlock();
  4641. /*
  4642. * Only show locks if all tasks are dumped:
  4643. */
  4644. if (!state_filter)
  4645. debug_show_all_locks();
  4646. }
  4647. /**
  4648. * init_idle - set up an idle thread for a given CPU
  4649. * @idle: task in question
  4650. * @cpu: CPU the idle task belongs to
  4651. *
  4652. * NOTE: this function does not set the idle thread's NEED_RESCHED
  4653. * flag, to make booting more robust.
  4654. */
  4655. void init_idle(struct task_struct *idle, int cpu)
  4656. {
  4657. struct rq *rq = cpu_rq(cpu);
  4658. unsigned long flags;
  4659. raw_spin_lock_irqsave(&idle->pi_lock, flags);
  4660. raw_spin_lock(&rq->lock);
  4661. __sched_fork(0, idle);
  4662. idle->state = TASK_RUNNING;
  4663. idle->se.exec_start = sched_clock();
  4664. idle->flags |= PF_IDLE;
  4665. kasan_unpoison_task_stack(idle);
  4666. #ifdef CONFIG_SMP
  4667. /*
  4668. * Its possible that init_idle() gets called multiple times on a task,
  4669. * in that case do_set_cpus_allowed() will not do the right thing.
  4670. *
  4671. * And since this is boot we can forgo the serialization.
  4672. */
  4673. set_cpus_allowed_common(idle, cpumask_of(cpu));
  4674. #endif
  4675. /*
  4676. * We're having a chicken and egg problem, even though we are
  4677. * holding rq->lock, the CPU isn't yet set to this CPU so the
  4678. * lockdep check in task_group() will fail.
  4679. *
  4680. * Similar case to sched_fork(). / Alternatively we could
  4681. * use task_rq_lock() here and obtain the other rq->lock.
  4682. *
  4683. * Silence PROVE_RCU
  4684. */
  4685. rcu_read_lock();
  4686. __set_task_cpu(idle, cpu);
  4687. rcu_read_unlock();
  4688. rq->curr = rq->idle = idle;
  4689. idle->on_rq = TASK_ON_RQ_QUEUED;
  4690. #ifdef CONFIG_SMP
  4691. idle->on_cpu = 1;
  4692. #endif
  4693. raw_spin_unlock(&rq->lock);
  4694. raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
  4695. /* Set the preempt count _outside_ the spinlocks! */
  4696. init_idle_preempt_count(idle, cpu);
  4697. /*
  4698. * The idle tasks have their own, simple scheduling class:
  4699. */
  4700. idle->sched_class = &idle_sched_class;
  4701. ftrace_graph_init_idle_task(idle, cpu);
  4702. vtime_init_idle(idle, cpu);
  4703. #ifdef CONFIG_SMP
  4704. sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
  4705. #endif
  4706. }
  4707. #ifdef CONFIG_SMP
  4708. int cpuset_cpumask_can_shrink(const struct cpumask *cur,
  4709. const struct cpumask *trial)
  4710. {
  4711. int ret = 1;
  4712. if (!cpumask_weight(cur))
  4713. return ret;
  4714. ret = dl_cpuset_cpumask_can_shrink(cur, trial);
  4715. return ret;
  4716. }
  4717. int task_can_attach(struct task_struct *p,
  4718. const struct cpumask *cs_cpus_allowed)
  4719. {
  4720. int ret = 0;
  4721. /*
  4722. * Kthreads which disallow setaffinity shouldn't be moved
  4723. * to a new cpuset; we don't want to change their CPU
  4724. * affinity and isolating such threads by their set of
  4725. * allowed nodes is unnecessary. Thus, cpusets are not
  4726. * applicable for such threads. This prevents checking for
  4727. * success of set_cpus_allowed_ptr() on all attached tasks
  4728. * before cpus_allowed may be changed.
  4729. */
  4730. if (p->flags & PF_NO_SETAFFINITY) {
  4731. ret = -EINVAL;
  4732. goto out;
  4733. }
  4734. if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
  4735. cs_cpus_allowed))
  4736. ret = dl_task_can_attach(p, cs_cpus_allowed);
  4737. out:
  4738. return ret;
  4739. }
  4740. bool sched_smp_initialized __read_mostly;
  4741. #ifdef CONFIG_NUMA_BALANCING
  4742. /* Migrate current task p to target_cpu */
  4743. int migrate_task_to(struct task_struct *p, int target_cpu)
  4744. {
  4745. struct migration_arg arg = { p, target_cpu };
  4746. int curr_cpu = task_cpu(p);
  4747. if (curr_cpu == target_cpu)
  4748. return 0;
  4749. if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
  4750. return -EINVAL;
  4751. /* TODO: This is not properly updating schedstats */
  4752. trace_sched_move_numa(p, curr_cpu, target_cpu);
  4753. return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
  4754. }
  4755. /*
  4756. * Requeue a task on a given node and accurately track the number of NUMA
  4757. * tasks on the runqueues
  4758. */
  4759. void sched_setnuma(struct task_struct *p, int nid)
  4760. {
  4761. bool queued, running;
  4762. struct rq_flags rf;
  4763. struct rq *rq;
  4764. rq = task_rq_lock(p, &rf);
  4765. queued = task_on_rq_queued(p);
  4766. running = task_current(rq, p);
  4767. if (queued)
  4768. dequeue_task(rq, p, DEQUEUE_SAVE);
  4769. if (running)
  4770. put_prev_task(rq, p);
  4771. p->numa_preferred_nid = nid;
  4772. if (queued)
  4773. enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
  4774. if (running)
  4775. set_curr_task(rq, p);
  4776. task_rq_unlock(rq, p, &rf);
  4777. }
  4778. #endif /* CONFIG_NUMA_BALANCING */
  4779. #ifdef CONFIG_HOTPLUG_CPU
  4780. /*
  4781. * Ensure that the idle task is using init_mm right before its CPU goes
  4782. * offline.
  4783. */
  4784. void idle_task_exit(void)
  4785. {
  4786. struct mm_struct *mm = current->active_mm;
  4787. BUG_ON(cpu_online(smp_processor_id()));
  4788. if (mm != &init_mm) {
  4789. switch_mm(mm, &init_mm, current);
  4790. finish_arch_post_lock_switch();
  4791. }
  4792. mmdrop(mm);
  4793. }
  4794. /*
  4795. * Since this CPU is going 'away' for a while, fold any nr_active delta
  4796. * we might have. Assumes we're called after migrate_tasks() so that the
  4797. * nr_active count is stable. We need to take the teardown thread which
  4798. * is calling this into account, so we hand in adjust = 1 to the load
  4799. * calculation.
  4800. *
  4801. * Also see the comment "Global load-average calculations".
  4802. */
  4803. static void calc_load_migrate(struct rq *rq)
  4804. {
  4805. long delta = calc_load_fold_active(rq, 1);
  4806. if (delta)
  4807. atomic_long_add(delta, &calc_load_tasks);
  4808. }
  4809. static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
  4810. {
  4811. }
  4812. static const struct sched_class fake_sched_class = {
  4813. .put_prev_task = put_prev_task_fake,
  4814. };
  4815. static struct task_struct fake_task = {
  4816. /*
  4817. * Avoid pull_{rt,dl}_task()
  4818. */
  4819. .prio = MAX_PRIO + 1,
  4820. .sched_class = &fake_sched_class,
  4821. };
  4822. /*
  4823. * Migrate all tasks from the rq, sleeping tasks will be migrated by
  4824. * try_to_wake_up()->select_task_rq().
  4825. *
  4826. * Called with rq->lock held even though we'er in stop_machine() and
  4827. * there's no concurrency possible, we hold the required locks anyway
  4828. * because of lock validation efforts.
  4829. */
  4830. static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
  4831. {
  4832. struct rq *rq = dead_rq;
  4833. struct task_struct *next, *stop = rq->stop;
  4834. struct rq_flags orf = *rf;
  4835. int dest_cpu;
  4836. /*
  4837. * Fudge the rq selection such that the below task selection loop
  4838. * doesn't get stuck on the currently eligible stop task.
  4839. *
  4840. * We're currently inside stop_machine() and the rq is either stuck
  4841. * in the stop_machine_cpu_stop() loop, or we're executing this code,
  4842. * either way we should never end up calling schedule() until we're
  4843. * done here.
  4844. */
  4845. rq->stop = NULL;
  4846. /*
  4847. * put_prev_task() and pick_next_task() sched
  4848. * class method both need to have an up-to-date
  4849. * value of rq->clock[_task]
  4850. */
  4851. update_rq_clock(rq);
  4852. for (;;) {
  4853. /*
  4854. * There's this thread running, bail when that's the only
  4855. * remaining thread:
  4856. */
  4857. if (rq->nr_running == 1)
  4858. break;
  4859. /*
  4860. * pick_next_task() assumes pinned rq->lock:
  4861. */
  4862. next = pick_next_task(rq, &fake_task, rf);
  4863. BUG_ON(!next);
  4864. put_prev_task(rq, next);
  4865. /*
  4866. * Rules for changing task_struct::cpus_allowed are holding
  4867. * both pi_lock and rq->lock, such that holding either
  4868. * stabilizes the mask.
  4869. *
  4870. * Drop rq->lock is not quite as disastrous as it usually is
  4871. * because !cpu_active at this point, which means load-balance
  4872. * will not interfere. Also, stop-machine.
  4873. */
  4874. rq_unlock(rq, rf);
  4875. raw_spin_lock(&next->pi_lock);
  4876. rq_relock(rq, rf);
  4877. /*
  4878. * Since we're inside stop-machine, _nothing_ should have
  4879. * changed the task, WARN if weird stuff happened, because in
  4880. * that case the above rq->lock drop is a fail too.
  4881. */
  4882. if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
  4883. raw_spin_unlock(&next->pi_lock);
  4884. continue;
  4885. }
  4886. /* Find suitable destination for @next, with force if needed. */
  4887. dest_cpu = select_fallback_rq(dead_rq->cpu, next);
  4888. rq = __migrate_task(rq, rf, next, dest_cpu);
  4889. if (rq != dead_rq) {
  4890. rq_unlock(rq, rf);
  4891. rq = dead_rq;
  4892. *rf = orf;
  4893. rq_relock(rq, rf);
  4894. }
  4895. raw_spin_unlock(&next->pi_lock);
  4896. }
  4897. rq->stop = stop;
  4898. }
  4899. #endif /* CONFIG_HOTPLUG_CPU */
  4900. void set_rq_online(struct rq *rq)
  4901. {
  4902. if (!rq->online) {
  4903. const struct sched_class *class;
  4904. cpumask_set_cpu(rq->cpu, rq->rd->online);
  4905. rq->online = 1;
  4906. for_each_class(class) {
  4907. if (class->rq_online)
  4908. class->rq_online(rq);
  4909. }
  4910. }
  4911. }
  4912. void set_rq_offline(struct rq *rq)
  4913. {
  4914. if (rq->online) {
  4915. const struct sched_class *class;
  4916. for_each_class(class) {
  4917. if (class->rq_offline)
  4918. class->rq_offline(rq);
  4919. }
  4920. cpumask_clear_cpu(rq->cpu, rq->rd->online);
  4921. rq->online = 0;
  4922. }
  4923. }
  4924. static void set_cpu_rq_start_time(unsigned int cpu)
  4925. {
  4926. struct rq *rq = cpu_rq(cpu);
  4927. rq->age_stamp = sched_clock_cpu(cpu);
  4928. }
  4929. /*
  4930. * used to mark begin/end of suspend/resume:
  4931. */
  4932. static int num_cpus_frozen;
  4933. /*
  4934. * Update cpusets according to cpu_active mask. If cpusets are
  4935. * disabled, cpuset_update_active_cpus() becomes a simple wrapper
  4936. * around partition_sched_domains().
  4937. *
  4938. * If we come here as part of a suspend/resume, don't touch cpusets because we
  4939. * want to restore it back to its original state upon resume anyway.
  4940. */
  4941. static void cpuset_cpu_active(void)
  4942. {
  4943. if (cpuhp_tasks_frozen) {
  4944. /*
  4945. * num_cpus_frozen tracks how many CPUs are involved in suspend
  4946. * resume sequence. As long as this is not the last online
  4947. * operation in the resume sequence, just build a single sched
  4948. * domain, ignoring cpusets.
  4949. */
  4950. partition_sched_domains(1, NULL, NULL);
  4951. if (--num_cpus_frozen)
  4952. return;
  4953. /*
  4954. * This is the last CPU online operation. So fall through and
  4955. * restore the original sched domains by considering the
  4956. * cpuset configurations.
  4957. */
  4958. cpuset_force_rebuild();
  4959. }
  4960. cpuset_update_active_cpus();
  4961. }
  4962. static int cpuset_cpu_inactive(unsigned int cpu)
  4963. {
  4964. if (!cpuhp_tasks_frozen) {
  4965. if (dl_cpu_busy(cpu))
  4966. return -EBUSY;
  4967. cpuset_update_active_cpus();
  4968. } else {
  4969. num_cpus_frozen++;
  4970. partition_sched_domains(1, NULL, NULL);
  4971. }
  4972. return 0;
  4973. }
  4974. int sched_cpu_activate(unsigned int cpu)
  4975. {
  4976. struct rq *rq = cpu_rq(cpu);
  4977. struct rq_flags rf;
  4978. set_cpu_active(cpu, true);
  4979. if (sched_smp_initialized) {
  4980. sched_domains_numa_masks_set(cpu);
  4981. cpuset_cpu_active();
  4982. }
  4983. /*
  4984. * Put the rq online, if not already. This happens:
  4985. *
  4986. * 1) In the early boot process, because we build the real domains
  4987. * after all CPUs have been brought up.
  4988. *
  4989. * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
  4990. * domains.
  4991. */
  4992. rq_lock_irqsave(rq, &rf);
  4993. if (rq->rd) {
  4994. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  4995. set_rq_online(rq);
  4996. }
  4997. rq_unlock_irqrestore(rq, &rf);
  4998. update_max_interval();
  4999. return 0;
  5000. }
  5001. int sched_cpu_deactivate(unsigned int cpu)
  5002. {
  5003. int ret;
  5004. set_cpu_active(cpu, false);
  5005. /*
  5006. * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
  5007. * users of this state to go away such that all new such users will
  5008. * observe it.
  5009. *
  5010. * Do sync before park smpboot threads to take care the rcu boost case.
  5011. */
  5012. synchronize_rcu_mult(call_rcu, call_rcu_sched);
  5013. if (!sched_smp_initialized)
  5014. return 0;
  5015. ret = cpuset_cpu_inactive(cpu);
  5016. if (ret) {
  5017. set_cpu_active(cpu, true);
  5018. return ret;
  5019. }
  5020. sched_domains_numa_masks_clear(cpu);
  5021. return 0;
  5022. }
  5023. static void sched_rq_cpu_starting(unsigned int cpu)
  5024. {
  5025. struct rq *rq = cpu_rq(cpu);
  5026. rq->calc_load_update = calc_load_update;
  5027. update_max_interval();
  5028. }
  5029. int sched_cpu_starting(unsigned int cpu)
  5030. {
  5031. set_cpu_rq_start_time(cpu);
  5032. sched_rq_cpu_starting(cpu);
  5033. sched_tick_start(cpu);
  5034. return 0;
  5035. }
  5036. #ifdef CONFIG_HOTPLUG_CPU
  5037. int sched_cpu_dying(unsigned int cpu)
  5038. {
  5039. struct rq *rq = cpu_rq(cpu);
  5040. struct rq_flags rf;
  5041. /* Handle pending wakeups and then migrate everything off */
  5042. sched_ttwu_pending();
  5043. sched_tick_stop(cpu);
  5044. rq_lock_irqsave(rq, &rf);
  5045. if (rq->rd) {
  5046. BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
  5047. set_rq_offline(rq);
  5048. }
  5049. migrate_tasks(rq, &rf);
  5050. BUG_ON(rq->nr_running != 1);
  5051. rq_unlock_irqrestore(rq, &rf);
  5052. calc_load_migrate(rq);
  5053. update_max_interval();
  5054. nohz_balance_exit_idle(cpu);
  5055. hrtick_clear(rq);
  5056. return 0;
  5057. }
  5058. #endif
  5059. #ifdef CONFIG_SCHED_SMT
  5060. DEFINE_STATIC_KEY_FALSE(sched_smt_present);
  5061. static void sched_init_smt(void)
  5062. {
  5063. /*
  5064. * We've enumerated all CPUs and will assume that if any CPU
  5065. * has SMT siblings, CPU0 will too.
  5066. */
  5067. if (cpumask_weight(cpu_smt_mask(0)) > 1)
  5068. static_branch_enable(&sched_smt_present);
  5069. }
  5070. #else
  5071. static inline void sched_init_smt(void) { }
  5072. #endif
  5073. void __init sched_init_smp(void)
  5074. {
  5075. sched_init_numa();
  5076. /*
  5077. * There's no userspace yet to cause hotplug operations; hence all the
  5078. * CPU masks are stable and all blatant races in the below code cannot
  5079. * happen.
  5080. */
  5081. mutex_lock(&sched_domains_mutex);
  5082. sched_init_domains(cpu_active_mask);
  5083. mutex_unlock(&sched_domains_mutex);
  5084. /* Move init over to a non-isolated CPU */
  5085. if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
  5086. BUG();
  5087. sched_init_granularity();
  5088. init_sched_rt_class();
  5089. init_sched_dl_class();
  5090. sched_init_smt();
  5091. sched_smp_initialized = true;
  5092. }
  5093. static int __init migration_init(void)
  5094. {
  5095. sched_rq_cpu_starting(smp_processor_id());
  5096. return 0;
  5097. }
  5098. early_initcall(migration_init);
  5099. #else
  5100. void __init sched_init_smp(void)
  5101. {
  5102. sched_init_granularity();
  5103. }
  5104. #endif /* CONFIG_SMP */
  5105. int in_sched_functions(unsigned long addr)
  5106. {
  5107. return in_lock_functions(addr) ||
  5108. (addr >= (unsigned long)__sched_text_start
  5109. && addr < (unsigned long)__sched_text_end);
  5110. }
  5111. #ifdef CONFIG_CGROUP_SCHED
  5112. /*
  5113. * Default task group.
  5114. * Every task in system belongs to this group at bootup.
  5115. */
  5116. struct task_group root_task_group;
  5117. LIST_HEAD(task_groups);
  5118. /* Cacheline aligned slab cache for task_group */
  5119. static struct kmem_cache *task_group_cache __read_mostly;
  5120. #endif
  5121. DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
  5122. DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
  5123. void __init sched_init(void)
  5124. {
  5125. int i, j;
  5126. unsigned long alloc_size = 0, ptr;
  5127. sched_clock_init();
  5128. wait_bit_init();
  5129. #ifdef CONFIG_FAIR_GROUP_SCHED
  5130. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  5131. #endif
  5132. #ifdef CONFIG_RT_GROUP_SCHED
  5133. alloc_size += 2 * nr_cpu_ids * sizeof(void **);
  5134. #endif
  5135. if (alloc_size) {
  5136. ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
  5137. #ifdef CONFIG_FAIR_GROUP_SCHED
  5138. root_task_group.se = (struct sched_entity **)ptr;
  5139. ptr += nr_cpu_ids * sizeof(void **);
  5140. root_task_group.cfs_rq = (struct cfs_rq **)ptr;
  5141. ptr += nr_cpu_ids * sizeof(void **);
  5142. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5143. #ifdef CONFIG_RT_GROUP_SCHED
  5144. root_task_group.rt_se = (struct sched_rt_entity **)ptr;
  5145. ptr += nr_cpu_ids * sizeof(void **);
  5146. root_task_group.rt_rq = (struct rt_rq **)ptr;
  5147. ptr += nr_cpu_ids * sizeof(void **);
  5148. #endif /* CONFIG_RT_GROUP_SCHED */
  5149. }
  5150. #ifdef CONFIG_CPUMASK_OFFSTACK
  5151. for_each_possible_cpu(i) {
  5152. per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
  5153. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  5154. per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
  5155. cpumask_size(), GFP_KERNEL, cpu_to_node(i));
  5156. }
  5157. #endif /* CONFIG_CPUMASK_OFFSTACK */
  5158. init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
  5159. init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
  5160. #ifdef CONFIG_SMP
  5161. init_defrootdomain();
  5162. #endif
  5163. #ifdef CONFIG_RT_GROUP_SCHED
  5164. init_rt_bandwidth(&root_task_group.rt_bandwidth,
  5165. global_rt_period(), global_rt_runtime());
  5166. #endif /* CONFIG_RT_GROUP_SCHED */
  5167. #ifdef CONFIG_CGROUP_SCHED
  5168. task_group_cache = KMEM_CACHE(task_group, 0);
  5169. list_add(&root_task_group.list, &task_groups);
  5170. INIT_LIST_HEAD(&root_task_group.children);
  5171. INIT_LIST_HEAD(&root_task_group.siblings);
  5172. autogroup_init(&init_task);
  5173. #endif /* CONFIG_CGROUP_SCHED */
  5174. for_each_possible_cpu(i) {
  5175. struct rq *rq;
  5176. rq = cpu_rq(i);
  5177. raw_spin_lock_init(&rq->lock);
  5178. rq->nr_running = 0;
  5179. rq->calc_load_active = 0;
  5180. rq->calc_load_update = jiffies + LOAD_FREQ;
  5181. init_cfs_rq(&rq->cfs);
  5182. init_rt_rq(&rq->rt);
  5183. init_dl_rq(&rq->dl);
  5184. #ifdef CONFIG_FAIR_GROUP_SCHED
  5185. root_task_group.shares = ROOT_TASK_GROUP_LOAD;
  5186. INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
  5187. rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
  5188. /*
  5189. * How much CPU bandwidth does root_task_group get?
  5190. *
  5191. * In case of task-groups formed thr' the cgroup filesystem, it
  5192. * gets 100% of the CPU resources in the system. This overall
  5193. * system CPU resource is divided among the tasks of
  5194. * root_task_group and its child task-groups in a fair manner,
  5195. * based on each entity's (task or task-group's) weight
  5196. * (se->load.weight).
  5197. *
  5198. * In other words, if root_task_group has 10 tasks of weight
  5199. * 1024) and two child groups A0 and A1 (of weight 1024 each),
  5200. * then A0's share of the CPU resource is:
  5201. *
  5202. * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
  5203. *
  5204. * We achieve this by letting root_task_group's tasks sit
  5205. * directly in rq->cfs (i.e root_task_group->se[] = NULL).
  5206. */
  5207. init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
  5208. init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
  5209. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5210. rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
  5211. #ifdef CONFIG_RT_GROUP_SCHED
  5212. init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
  5213. #endif
  5214. for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
  5215. rq->cpu_load[j] = 0;
  5216. #ifdef CONFIG_SMP
  5217. rq->sd = NULL;
  5218. rq->rd = NULL;
  5219. rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
  5220. rq->balance_callback = NULL;
  5221. rq->active_balance = 0;
  5222. rq->next_balance = jiffies;
  5223. rq->push_cpu = 0;
  5224. rq->cpu = i;
  5225. rq->online = 0;
  5226. rq->idle_stamp = 0;
  5227. rq->avg_idle = 2*sysctl_sched_migration_cost;
  5228. rq->max_idle_balance_cost = sysctl_sched_migration_cost;
  5229. INIT_LIST_HEAD(&rq->cfs_tasks);
  5230. rq_attach_root(rq, &def_root_domain);
  5231. #ifdef CONFIG_NO_HZ_COMMON
  5232. rq->last_load_update_tick = jiffies;
  5233. rq->nohz_flags = 0;
  5234. #endif
  5235. #endif /* CONFIG_SMP */
  5236. hrtick_rq_init(rq);
  5237. atomic_set(&rq->nr_iowait, 0);
  5238. }
  5239. set_load_weight(&init_task, false);
  5240. /*
  5241. * The boot idle thread does lazy MMU switching as well:
  5242. */
  5243. mmgrab(&init_mm);
  5244. enter_lazy_tlb(&init_mm, current);
  5245. /*
  5246. * Make us the idle thread. Technically, schedule() should not be
  5247. * called from this thread, however somewhere below it might be,
  5248. * but because we are the idle thread, we just pick up running again
  5249. * when this runqueue becomes "idle".
  5250. */
  5251. init_idle(current, smp_processor_id());
  5252. calc_load_update = jiffies + LOAD_FREQ;
  5253. #ifdef CONFIG_SMP
  5254. idle_thread_set_boot_cpu();
  5255. set_cpu_rq_start_time(smp_processor_id());
  5256. #endif
  5257. init_sched_fair_class();
  5258. init_schedstats();
  5259. scheduler_running = 1;
  5260. }
  5261. #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
  5262. static inline int preempt_count_equals(int preempt_offset)
  5263. {
  5264. int nested = preempt_count() + rcu_preempt_depth();
  5265. return (nested == preempt_offset);
  5266. }
  5267. void __might_sleep(const char *file, int line, int preempt_offset)
  5268. {
  5269. /*
  5270. * Blocking primitives will set (and therefore destroy) current->state,
  5271. * since we will exit with TASK_RUNNING make sure we enter with it,
  5272. * otherwise we will destroy state.
  5273. */
  5274. WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
  5275. "do not call blocking ops when !TASK_RUNNING; "
  5276. "state=%lx set at [<%p>] %pS\n",
  5277. current->state,
  5278. (void *)current->task_state_change,
  5279. (void *)current->task_state_change);
  5280. ___might_sleep(file, line, preempt_offset);
  5281. }
  5282. EXPORT_SYMBOL(__might_sleep);
  5283. void ___might_sleep(const char *file, int line, int preempt_offset)
  5284. {
  5285. /* Ratelimiting timestamp: */
  5286. static unsigned long prev_jiffy;
  5287. unsigned long preempt_disable_ip;
  5288. /* WARN_ON_ONCE() by default, no rate limit required: */
  5289. rcu_sleep_check();
  5290. if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
  5291. !is_idle_task(current)) ||
  5292. system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
  5293. oops_in_progress)
  5294. return;
  5295. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  5296. return;
  5297. prev_jiffy = jiffies;
  5298. /* Save this before calling printk(), since that will clobber it: */
  5299. preempt_disable_ip = get_preempt_disable_ip(current);
  5300. printk(KERN_ERR
  5301. "BUG: sleeping function called from invalid context at %s:%d\n",
  5302. file, line);
  5303. printk(KERN_ERR
  5304. "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
  5305. in_atomic(), irqs_disabled(),
  5306. current->pid, current->comm);
  5307. if (task_stack_end_corrupted(current))
  5308. printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
  5309. debug_show_held_locks(current);
  5310. if (irqs_disabled())
  5311. print_irqtrace_events(current);
  5312. if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
  5313. && !preempt_count_equals(preempt_offset)) {
  5314. pr_err("Preemption disabled at:");
  5315. print_ip_sym(preempt_disable_ip);
  5316. pr_cont("\n");
  5317. }
  5318. dump_stack();
  5319. add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
  5320. }
  5321. EXPORT_SYMBOL(___might_sleep);
  5322. #endif
  5323. #ifdef CONFIG_MAGIC_SYSRQ
  5324. void normalize_rt_tasks(void)
  5325. {
  5326. struct task_struct *g, *p;
  5327. struct sched_attr attr = {
  5328. .sched_policy = SCHED_NORMAL,
  5329. };
  5330. read_lock(&tasklist_lock);
  5331. for_each_process_thread(g, p) {
  5332. /*
  5333. * Only normalize user tasks:
  5334. */
  5335. if (p->flags & PF_KTHREAD)
  5336. continue;
  5337. p->se.exec_start = 0;
  5338. schedstat_set(p->se.statistics.wait_start, 0);
  5339. schedstat_set(p->se.statistics.sleep_start, 0);
  5340. schedstat_set(p->se.statistics.block_start, 0);
  5341. if (!dl_task(p) && !rt_task(p)) {
  5342. /*
  5343. * Renice negative nice level userspace
  5344. * tasks back to 0:
  5345. */
  5346. if (task_nice(p) < 0)
  5347. set_user_nice(p, 0);
  5348. continue;
  5349. }
  5350. __sched_setscheduler(p, &attr, false, false);
  5351. }
  5352. read_unlock(&tasklist_lock);
  5353. }
  5354. #endif /* CONFIG_MAGIC_SYSRQ */
  5355. #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
  5356. /*
  5357. * These functions are only useful for the IA64 MCA handling, or kdb.
  5358. *
  5359. * They can only be called when the whole system has been
  5360. * stopped - every CPU needs to be quiescent, and no scheduling
  5361. * activity can take place. Using them for anything else would
  5362. * be a serious bug, and as a result, they aren't even visible
  5363. * under any other configuration.
  5364. */
  5365. /**
  5366. * curr_task - return the current task for a given CPU.
  5367. * @cpu: the processor in question.
  5368. *
  5369. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5370. *
  5371. * Return: The current task for @cpu.
  5372. */
  5373. struct task_struct *curr_task(int cpu)
  5374. {
  5375. return cpu_curr(cpu);
  5376. }
  5377. #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
  5378. #ifdef CONFIG_IA64
  5379. /**
  5380. * set_curr_task - set the current task for a given CPU.
  5381. * @cpu: the processor in question.
  5382. * @p: the task pointer to set.
  5383. *
  5384. * Description: This function must only be used when non-maskable interrupts
  5385. * are serviced on a separate stack. It allows the architecture to switch the
  5386. * notion of the current task on a CPU in a non-blocking manner. This function
  5387. * must be called with all CPU's synchronized, and interrupts disabled, the
  5388. * and caller must save the original value of the current task (see
  5389. * curr_task() above) and restore that value before reenabling interrupts and
  5390. * re-starting the system.
  5391. *
  5392. * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
  5393. */
  5394. void ia64_set_curr_task(int cpu, struct task_struct *p)
  5395. {
  5396. cpu_curr(cpu) = p;
  5397. }
  5398. #endif
  5399. #ifdef CONFIG_CGROUP_SCHED
  5400. /* task_group_lock serializes the addition/removal of task groups */
  5401. static DEFINE_SPINLOCK(task_group_lock);
  5402. static void sched_free_group(struct task_group *tg)
  5403. {
  5404. free_fair_sched_group(tg);
  5405. free_rt_sched_group(tg);
  5406. autogroup_free(tg);
  5407. kmem_cache_free(task_group_cache, tg);
  5408. }
  5409. /* allocate runqueue etc for a new task group */
  5410. struct task_group *sched_create_group(struct task_group *parent)
  5411. {
  5412. struct task_group *tg;
  5413. tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
  5414. if (!tg)
  5415. return ERR_PTR(-ENOMEM);
  5416. if (!alloc_fair_sched_group(tg, parent))
  5417. goto err;
  5418. if (!alloc_rt_sched_group(tg, parent))
  5419. goto err;
  5420. return tg;
  5421. err:
  5422. sched_free_group(tg);
  5423. return ERR_PTR(-ENOMEM);
  5424. }
  5425. void sched_online_group(struct task_group *tg, struct task_group *parent)
  5426. {
  5427. unsigned long flags;
  5428. spin_lock_irqsave(&task_group_lock, flags);
  5429. list_add_rcu(&tg->list, &task_groups);
  5430. /* Root should already exist: */
  5431. WARN_ON(!parent);
  5432. tg->parent = parent;
  5433. INIT_LIST_HEAD(&tg->children);
  5434. list_add_rcu(&tg->siblings, &parent->children);
  5435. spin_unlock_irqrestore(&task_group_lock, flags);
  5436. online_fair_sched_group(tg);
  5437. }
  5438. /* rcu callback to free various structures associated with a task group */
  5439. static void sched_free_group_rcu(struct rcu_head *rhp)
  5440. {
  5441. /* Now it should be safe to free those cfs_rqs: */
  5442. sched_free_group(container_of(rhp, struct task_group, rcu));
  5443. }
  5444. void sched_destroy_group(struct task_group *tg)
  5445. {
  5446. /* Wait for possible concurrent references to cfs_rqs complete: */
  5447. call_rcu(&tg->rcu, sched_free_group_rcu);
  5448. }
  5449. void sched_offline_group(struct task_group *tg)
  5450. {
  5451. unsigned long flags;
  5452. /* End participation in shares distribution: */
  5453. unregister_fair_sched_group(tg);
  5454. spin_lock_irqsave(&task_group_lock, flags);
  5455. list_del_rcu(&tg->list);
  5456. list_del_rcu(&tg->siblings);
  5457. spin_unlock_irqrestore(&task_group_lock, flags);
  5458. }
  5459. static void sched_change_group(struct task_struct *tsk, int type)
  5460. {
  5461. struct task_group *tg;
  5462. /*
  5463. * All callers are synchronized by task_rq_lock(); we do not use RCU
  5464. * which is pointless here. Thus, we pass "true" to task_css_check()
  5465. * to prevent lockdep warnings.
  5466. */
  5467. tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
  5468. struct task_group, css);
  5469. tg = autogroup_task_group(tsk, tg);
  5470. tsk->sched_task_group = tg;
  5471. #ifdef CONFIG_FAIR_GROUP_SCHED
  5472. if (tsk->sched_class->task_change_group)
  5473. tsk->sched_class->task_change_group(tsk, type);
  5474. else
  5475. #endif
  5476. set_task_rq(tsk, task_cpu(tsk));
  5477. }
  5478. /*
  5479. * Change task's runqueue when it moves between groups.
  5480. *
  5481. * The caller of this function should have put the task in its new group by
  5482. * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
  5483. * its new group.
  5484. */
  5485. void sched_move_task(struct task_struct *tsk)
  5486. {
  5487. int queued, running, queue_flags =
  5488. DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
  5489. struct rq_flags rf;
  5490. struct rq *rq;
  5491. rq = task_rq_lock(tsk, &rf);
  5492. update_rq_clock(rq);
  5493. running = task_current(rq, tsk);
  5494. queued = task_on_rq_queued(tsk);
  5495. if (queued)
  5496. dequeue_task(rq, tsk, queue_flags);
  5497. if (running)
  5498. put_prev_task(rq, tsk);
  5499. sched_change_group(tsk, TASK_MOVE_GROUP);
  5500. if (queued)
  5501. enqueue_task(rq, tsk, queue_flags);
  5502. if (running)
  5503. set_curr_task(rq, tsk);
  5504. task_rq_unlock(rq, tsk, &rf);
  5505. }
  5506. static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
  5507. {
  5508. return css ? container_of(css, struct task_group, css) : NULL;
  5509. }
  5510. static struct cgroup_subsys_state *
  5511. cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
  5512. {
  5513. struct task_group *parent = css_tg(parent_css);
  5514. struct task_group *tg;
  5515. if (!parent) {
  5516. /* This is early initialization for the top cgroup */
  5517. return &root_task_group.css;
  5518. }
  5519. tg = sched_create_group(parent);
  5520. if (IS_ERR(tg))
  5521. return ERR_PTR(-ENOMEM);
  5522. return &tg->css;
  5523. }
  5524. /* Expose task group only after completing cgroup initialization */
  5525. static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
  5526. {
  5527. struct task_group *tg = css_tg(css);
  5528. struct task_group *parent = css_tg(css->parent);
  5529. if (parent)
  5530. sched_online_group(tg, parent);
  5531. return 0;
  5532. }
  5533. static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
  5534. {
  5535. struct task_group *tg = css_tg(css);
  5536. sched_offline_group(tg);
  5537. }
  5538. static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
  5539. {
  5540. struct task_group *tg = css_tg(css);
  5541. /*
  5542. * Relies on the RCU grace period between css_released() and this.
  5543. */
  5544. sched_free_group(tg);
  5545. }
  5546. /*
  5547. * This is called before wake_up_new_task(), therefore we really only
  5548. * have to set its group bits, all the other stuff does not apply.
  5549. */
  5550. static void cpu_cgroup_fork(struct task_struct *task)
  5551. {
  5552. struct rq_flags rf;
  5553. struct rq *rq;
  5554. rq = task_rq_lock(task, &rf);
  5555. update_rq_clock(rq);
  5556. sched_change_group(task, TASK_SET_GROUP);
  5557. task_rq_unlock(rq, task, &rf);
  5558. }
  5559. static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
  5560. {
  5561. struct task_struct *task;
  5562. struct cgroup_subsys_state *css;
  5563. int ret = 0;
  5564. cgroup_taskset_for_each(task, css, tset) {
  5565. #ifdef CONFIG_RT_GROUP_SCHED
  5566. if (!sched_rt_can_attach(css_tg(css), task))
  5567. return -EINVAL;
  5568. #else
  5569. /* We don't support RT-tasks being in separate groups */
  5570. if (task->sched_class != &fair_sched_class)
  5571. return -EINVAL;
  5572. #endif
  5573. /*
  5574. * Serialize against wake_up_new_task() such that if its
  5575. * running, we're sure to observe its full state.
  5576. */
  5577. raw_spin_lock_irq(&task->pi_lock);
  5578. /*
  5579. * Avoid calling sched_move_task() before wake_up_new_task()
  5580. * has happened. This would lead to problems with PELT, due to
  5581. * move wanting to detach+attach while we're not attached yet.
  5582. */
  5583. if (task->state == TASK_NEW)
  5584. ret = -EINVAL;
  5585. raw_spin_unlock_irq(&task->pi_lock);
  5586. if (ret)
  5587. break;
  5588. }
  5589. return ret;
  5590. }
  5591. static void cpu_cgroup_attach(struct cgroup_taskset *tset)
  5592. {
  5593. struct task_struct *task;
  5594. struct cgroup_subsys_state *css;
  5595. cgroup_taskset_for_each(task, css, tset)
  5596. sched_move_task(task);
  5597. }
  5598. #ifdef CONFIG_FAIR_GROUP_SCHED
  5599. static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
  5600. struct cftype *cftype, u64 shareval)
  5601. {
  5602. return sched_group_set_shares(css_tg(css), scale_load(shareval));
  5603. }
  5604. static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
  5605. struct cftype *cft)
  5606. {
  5607. struct task_group *tg = css_tg(css);
  5608. return (u64) scale_load_down(tg->shares);
  5609. }
  5610. #ifdef CONFIG_CFS_BANDWIDTH
  5611. static DEFINE_MUTEX(cfs_constraints_mutex);
  5612. const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
  5613. const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
  5614. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
  5615. static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
  5616. {
  5617. int i, ret = 0, runtime_enabled, runtime_was_enabled;
  5618. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5619. if (tg == &root_task_group)
  5620. return -EINVAL;
  5621. /*
  5622. * Ensure we have at some amount of bandwidth every period. This is
  5623. * to prevent reaching a state of large arrears when throttled via
  5624. * entity_tick() resulting in prolonged exit starvation.
  5625. */
  5626. if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
  5627. return -EINVAL;
  5628. /*
  5629. * Likewise, bound things on the otherside by preventing insane quota
  5630. * periods. This also allows us to normalize in computing quota
  5631. * feasibility.
  5632. */
  5633. if (period > max_cfs_quota_period)
  5634. return -EINVAL;
  5635. /*
  5636. * Prevent race between setting of cfs_rq->runtime_enabled and
  5637. * unthrottle_offline_cfs_rqs().
  5638. */
  5639. get_online_cpus();
  5640. mutex_lock(&cfs_constraints_mutex);
  5641. ret = __cfs_schedulable(tg, period, quota);
  5642. if (ret)
  5643. goto out_unlock;
  5644. runtime_enabled = quota != RUNTIME_INF;
  5645. runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
  5646. /*
  5647. * If we need to toggle cfs_bandwidth_used, off->on must occur
  5648. * before making related changes, and on->off must occur afterwards
  5649. */
  5650. if (runtime_enabled && !runtime_was_enabled)
  5651. cfs_bandwidth_usage_inc();
  5652. raw_spin_lock_irq(&cfs_b->lock);
  5653. cfs_b->period = ns_to_ktime(period);
  5654. cfs_b->quota = quota;
  5655. __refill_cfs_bandwidth_runtime(cfs_b);
  5656. /* Restart the period timer (if active) to handle new period expiry: */
  5657. if (runtime_enabled)
  5658. start_cfs_bandwidth(cfs_b);
  5659. raw_spin_unlock_irq(&cfs_b->lock);
  5660. for_each_online_cpu(i) {
  5661. struct cfs_rq *cfs_rq = tg->cfs_rq[i];
  5662. struct rq *rq = cfs_rq->rq;
  5663. struct rq_flags rf;
  5664. rq_lock_irq(rq, &rf);
  5665. cfs_rq->runtime_enabled = runtime_enabled;
  5666. cfs_rq->runtime_remaining = 0;
  5667. if (cfs_rq->throttled)
  5668. unthrottle_cfs_rq(cfs_rq);
  5669. rq_unlock_irq(rq, &rf);
  5670. }
  5671. if (runtime_was_enabled && !runtime_enabled)
  5672. cfs_bandwidth_usage_dec();
  5673. out_unlock:
  5674. mutex_unlock(&cfs_constraints_mutex);
  5675. put_online_cpus();
  5676. return ret;
  5677. }
  5678. int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
  5679. {
  5680. u64 quota, period;
  5681. period = ktime_to_ns(tg->cfs_bandwidth.period);
  5682. if (cfs_quota_us < 0)
  5683. quota = RUNTIME_INF;
  5684. else
  5685. quota = (u64)cfs_quota_us * NSEC_PER_USEC;
  5686. return tg_set_cfs_bandwidth(tg, period, quota);
  5687. }
  5688. long tg_get_cfs_quota(struct task_group *tg)
  5689. {
  5690. u64 quota_us;
  5691. if (tg->cfs_bandwidth.quota == RUNTIME_INF)
  5692. return -1;
  5693. quota_us = tg->cfs_bandwidth.quota;
  5694. do_div(quota_us, NSEC_PER_USEC);
  5695. return quota_us;
  5696. }
  5697. int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
  5698. {
  5699. u64 quota, period;
  5700. period = (u64)cfs_period_us * NSEC_PER_USEC;
  5701. quota = tg->cfs_bandwidth.quota;
  5702. return tg_set_cfs_bandwidth(tg, period, quota);
  5703. }
  5704. long tg_get_cfs_period(struct task_group *tg)
  5705. {
  5706. u64 cfs_period_us;
  5707. cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
  5708. do_div(cfs_period_us, NSEC_PER_USEC);
  5709. return cfs_period_us;
  5710. }
  5711. static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
  5712. struct cftype *cft)
  5713. {
  5714. return tg_get_cfs_quota(css_tg(css));
  5715. }
  5716. static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
  5717. struct cftype *cftype, s64 cfs_quota_us)
  5718. {
  5719. return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
  5720. }
  5721. static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
  5722. struct cftype *cft)
  5723. {
  5724. return tg_get_cfs_period(css_tg(css));
  5725. }
  5726. static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
  5727. struct cftype *cftype, u64 cfs_period_us)
  5728. {
  5729. return tg_set_cfs_period(css_tg(css), cfs_period_us);
  5730. }
  5731. struct cfs_schedulable_data {
  5732. struct task_group *tg;
  5733. u64 period, quota;
  5734. };
  5735. /*
  5736. * normalize group quota/period to be quota/max_period
  5737. * note: units are usecs
  5738. */
  5739. static u64 normalize_cfs_quota(struct task_group *tg,
  5740. struct cfs_schedulable_data *d)
  5741. {
  5742. u64 quota, period;
  5743. if (tg == d->tg) {
  5744. period = d->period;
  5745. quota = d->quota;
  5746. } else {
  5747. period = tg_get_cfs_period(tg);
  5748. quota = tg_get_cfs_quota(tg);
  5749. }
  5750. /* note: these should typically be equivalent */
  5751. if (quota == RUNTIME_INF || quota == -1)
  5752. return RUNTIME_INF;
  5753. return to_ratio(period, quota);
  5754. }
  5755. static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
  5756. {
  5757. struct cfs_schedulable_data *d = data;
  5758. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5759. s64 quota = 0, parent_quota = -1;
  5760. if (!tg->parent) {
  5761. quota = RUNTIME_INF;
  5762. } else {
  5763. struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
  5764. quota = normalize_cfs_quota(tg, d);
  5765. parent_quota = parent_b->hierarchical_quota;
  5766. /*
  5767. * Ensure max(child_quota) <= parent_quota, inherit when no
  5768. * limit is set:
  5769. */
  5770. if (quota == RUNTIME_INF)
  5771. quota = parent_quota;
  5772. else if (parent_quota != RUNTIME_INF && quota > parent_quota)
  5773. return -EINVAL;
  5774. }
  5775. cfs_b->hierarchical_quota = quota;
  5776. return 0;
  5777. }
  5778. static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
  5779. {
  5780. int ret;
  5781. struct cfs_schedulable_data data = {
  5782. .tg = tg,
  5783. .period = period,
  5784. .quota = quota,
  5785. };
  5786. if (quota != RUNTIME_INF) {
  5787. do_div(data.period, NSEC_PER_USEC);
  5788. do_div(data.quota, NSEC_PER_USEC);
  5789. }
  5790. rcu_read_lock();
  5791. ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
  5792. rcu_read_unlock();
  5793. return ret;
  5794. }
  5795. static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
  5796. {
  5797. struct task_group *tg = css_tg(seq_css(sf));
  5798. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5799. seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
  5800. seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
  5801. seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
  5802. return 0;
  5803. }
  5804. #endif /* CONFIG_CFS_BANDWIDTH */
  5805. #endif /* CONFIG_FAIR_GROUP_SCHED */
  5806. #ifdef CONFIG_RT_GROUP_SCHED
  5807. static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
  5808. struct cftype *cft, s64 val)
  5809. {
  5810. return sched_group_set_rt_runtime(css_tg(css), val);
  5811. }
  5812. static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
  5813. struct cftype *cft)
  5814. {
  5815. return sched_group_rt_runtime(css_tg(css));
  5816. }
  5817. static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
  5818. struct cftype *cftype, u64 rt_period_us)
  5819. {
  5820. return sched_group_set_rt_period(css_tg(css), rt_period_us);
  5821. }
  5822. static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
  5823. struct cftype *cft)
  5824. {
  5825. return sched_group_rt_period(css_tg(css));
  5826. }
  5827. #endif /* CONFIG_RT_GROUP_SCHED */
  5828. static struct cftype cpu_legacy_files[] = {
  5829. #ifdef CONFIG_FAIR_GROUP_SCHED
  5830. {
  5831. .name = "shares",
  5832. .read_u64 = cpu_shares_read_u64,
  5833. .write_u64 = cpu_shares_write_u64,
  5834. },
  5835. #endif
  5836. #ifdef CONFIG_CFS_BANDWIDTH
  5837. {
  5838. .name = "cfs_quota_us",
  5839. .read_s64 = cpu_cfs_quota_read_s64,
  5840. .write_s64 = cpu_cfs_quota_write_s64,
  5841. },
  5842. {
  5843. .name = "cfs_period_us",
  5844. .read_u64 = cpu_cfs_period_read_u64,
  5845. .write_u64 = cpu_cfs_period_write_u64,
  5846. },
  5847. {
  5848. .name = "stat",
  5849. .seq_show = cpu_cfs_stat_show,
  5850. },
  5851. #endif
  5852. #ifdef CONFIG_RT_GROUP_SCHED
  5853. {
  5854. .name = "rt_runtime_us",
  5855. .read_s64 = cpu_rt_runtime_read,
  5856. .write_s64 = cpu_rt_runtime_write,
  5857. },
  5858. {
  5859. .name = "rt_period_us",
  5860. .read_u64 = cpu_rt_period_read_uint,
  5861. .write_u64 = cpu_rt_period_write_uint,
  5862. },
  5863. #endif
  5864. { } /* Terminate */
  5865. };
  5866. static int cpu_extra_stat_show(struct seq_file *sf,
  5867. struct cgroup_subsys_state *css)
  5868. {
  5869. #ifdef CONFIG_CFS_BANDWIDTH
  5870. {
  5871. struct task_group *tg = css_tg(css);
  5872. struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
  5873. u64 throttled_usec;
  5874. throttled_usec = cfs_b->throttled_time;
  5875. do_div(throttled_usec, NSEC_PER_USEC);
  5876. seq_printf(sf, "nr_periods %d\n"
  5877. "nr_throttled %d\n"
  5878. "throttled_usec %llu\n",
  5879. cfs_b->nr_periods, cfs_b->nr_throttled,
  5880. throttled_usec);
  5881. }
  5882. #endif
  5883. return 0;
  5884. }
  5885. #ifdef CONFIG_FAIR_GROUP_SCHED
  5886. static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
  5887. struct cftype *cft)
  5888. {
  5889. struct task_group *tg = css_tg(css);
  5890. u64 weight = scale_load_down(tg->shares);
  5891. return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
  5892. }
  5893. static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
  5894. struct cftype *cft, u64 weight)
  5895. {
  5896. /*
  5897. * cgroup weight knobs should use the common MIN, DFL and MAX
  5898. * values which are 1, 100 and 10000 respectively. While it loses
  5899. * a bit of range on both ends, it maps pretty well onto the shares
  5900. * value used by scheduler and the round-trip conversions preserve
  5901. * the original value over the entire range.
  5902. */
  5903. if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
  5904. return -ERANGE;
  5905. weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
  5906. return sched_group_set_shares(css_tg(css), scale_load(weight));
  5907. }
  5908. static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
  5909. struct cftype *cft)
  5910. {
  5911. unsigned long weight = scale_load_down(css_tg(css)->shares);
  5912. int last_delta = INT_MAX;
  5913. int prio, delta;
  5914. /* find the closest nice value to the current weight */
  5915. for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
  5916. delta = abs(sched_prio_to_weight[prio] - weight);
  5917. if (delta >= last_delta)
  5918. break;
  5919. last_delta = delta;
  5920. }
  5921. return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
  5922. }
  5923. static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
  5924. struct cftype *cft, s64 nice)
  5925. {
  5926. unsigned long weight;
  5927. if (nice < MIN_NICE || nice > MAX_NICE)
  5928. return -ERANGE;
  5929. weight = sched_prio_to_weight[NICE_TO_PRIO(nice) - MAX_RT_PRIO];
  5930. return sched_group_set_shares(css_tg(css), scale_load(weight));
  5931. }
  5932. #endif
  5933. static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
  5934. long period, long quota)
  5935. {
  5936. if (quota < 0)
  5937. seq_puts(sf, "max");
  5938. else
  5939. seq_printf(sf, "%ld", quota);
  5940. seq_printf(sf, " %ld\n", period);
  5941. }
  5942. /* caller should put the current value in *@periodp before calling */
  5943. static int __maybe_unused cpu_period_quota_parse(char *buf,
  5944. u64 *periodp, u64 *quotap)
  5945. {
  5946. char tok[21]; /* U64_MAX */
  5947. if (!sscanf(buf, "%s %llu", tok, periodp))
  5948. return -EINVAL;
  5949. *periodp *= NSEC_PER_USEC;
  5950. if (sscanf(tok, "%llu", quotap))
  5951. *quotap *= NSEC_PER_USEC;
  5952. else if (!strcmp(tok, "max"))
  5953. *quotap = RUNTIME_INF;
  5954. else
  5955. return -EINVAL;
  5956. return 0;
  5957. }
  5958. #ifdef CONFIG_CFS_BANDWIDTH
  5959. static int cpu_max_show(struct seq_file *sf, void *v)
  5960. {
  5961. struct task_group *tg = css_tg(seq_css(sf));
  5962. cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
  5963. return 0;
  5964. }
  5965. static ssize_t cpu_max_write(struct kernfs_open_file *of,
  5966. char *buf, size_t nbytes, loff_t off)
  5967. {
  5968. struct task_group *tg = css_tg(of_css(of));
  5969. u64 period = tg_get_cfs_period(tg);
  5970. u64 quota;
  5971. int ret;
  5972. ret = cpu_period_quota_parse(buf, &period, &quota);
  5973. if (!ret)
  5974. ret = tg_set_cfs_bandwidth(tg, period, quota);
  5975. return ret ?: nbytes;
  5976. }
  5977. #endif
  5978. static struct cftype cpu_files[] = {
  5979. #ifdef CONFIG_FAIR_GROUP_SCHED
  5980. {
  5981. .name = "weight",
  5982. .flags = CFTYPE_NOT_ON_ROOT,
  5983. .read_u64 = cpu_weight_read_u64,
  5984. .write_u64 = cpu_weight_write_u64,
  5985. },
  5986. {
  5987. .name = "weight.nice",
  5988. .flags = CFTYPE_NOT_ON_ROOT,
  5989. .read_s64 = cpu_weight_nice_read_s64,
  5990. .write_s64 = cpu_weight_nice_write_s64,
  5991. },
  5992. #endif
  5993. #ifdef CONFIG_CFS_BANDWIDTH
  5994. {
  5995. .name = "max",
  5996. .flags = CFTYPE_NOT_ON_ROOT,
  5997. .seq_show = cpu_max_show,
  5998. .write = cpu_max_write,
  5999. },
  6000. #endif
  6001. { } /* terminate */
  6002. };
  6003. struct cgroup_subsys cpu_cgrp_subsys = {
  6004. .css_alloc = cpu_cgroup_css_alloc,
  6005. .css_online = cpu_cgroup_css_online,
  6006. .css_released = cpu_cgroup_css_released,
  6007. .css_free = cpu_cgroup_css_free,
  6008. .css_extra_stat_show = cpu_extra_stat_show,
  6009. .fork = cpu_cgroup_fork,
  6010. .can_attach = cpu_cgroup_can_attach,
  6011. .attach = cpu_cgroup_attach,
  6012. .legacy_cftypes = cpu_legacy_files,
  6013. .dfl_cftypes = cpu_files,
  6014. .early_init = true,
  6015. .threaded = true,
  6016. };
  6017. #endif /* CONFIG_CGROUP_SCHED */
  6018. void dump_cpu_task(int cpu)
  6019. {
  6020. pr_info("Task dump for CPU %d:\n", cpu);
  6021. sched_show_task(cpu_curr(cpu));
  6022. }
  6023. /*
  6024. * Nice levels are multiplicative, with a gentle 10% change for every
  6025. * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
  6026. * nice 1, it will get ~10% less CPU time than another CPU-bound task
  6027. * that remained on nice 0.
  6028. *
  6029. * The "10% effect" is relative and cumulative: from _any_ nice level,
  6030. * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
  6031. * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
  6032. * If a task goes up by ~10% and another task goes down by ~10% then
  6033. * the relative distance between them is ~25%.)
  6034. */
  6035. const int sched_prio_to_weight[40] = {
  6036. /* -20 */ 88761, 71755, 56483, 46273, 36291,
  6037. /* -15 */ 29154, 23254, 18705, 14949, 11916,
  6038. /* -10 */ 9548, 7620, 6100, 4904, 3906,
  6039. /* -5 */ 3121, 2501, 1991, 1586, 1277,
  6040. /* 0 */ 1024, 820, 655, 526, 423,
  6041. /* 5 */ 335, 272, 215, 172, 137,
  6042. /* 10 */ 110, 87, 70, 56, 45,
  6043. /* 15 */ 36, 29, 23, 18, 15,
  6044. };
  6045. /*
  6046. * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
  6047. *
  6048. * In cases where the weight does not change often, we can use the
  6049. * precalculated inverse to speed up arithmetics by turning divisions
  6050. * into multiplications:
  6051. */
  6052. const u32 sched_prio_to_wmult[40] = {
  6053. /* -20 */ 48388, 59856, 76040, 92818, 118348,
  6054. /* -15 */ 147320, 184698, 229616, 287308, 360437,
  6055. /* -10 */ 449829, 563644, 704093, 875809, 1099582,
  6056. /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
  6057. /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
  6058. /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
  6059. /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
  6060. /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
  6061. };