core.c 165 KB

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