core.c 181 KB

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