core.c 225 KB

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