core.c 178 KB

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