sched.c 138 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599
  1. /*
  2. * kernel/sched.c
  3. *
  4. * Kernel scheduler and related syscalls
  5. *
  6. * Copyright (C) 1991-2002 Linus Torvalds
  7. *
  8. * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
  9. * make semaphores SMP safe
  10. * 1998-11-19 Implemented schedule_timeout() and related stuff
  11. * by Andrea Arcangeli
  12. * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
  13. * hybrid priority-list and round-robin design with
  14. * an array-switch method of distributing timeslices
  15. * and per-CPU runqueues. Cleanups and useful suggestions
  16. * by Davide Libenzi, preemptible kernel bits by Robert Love.
  17. * 2003-09-03 Interactivity tuning by Con Kolivas.
  18. * 2004-04-02 Scheduler domains code by Nick Piggin
  19. */
  20. #include <linux/mm.h>
  21. #include <linux/module.h>
  22. #include <linux/nmi.h>
  23. #include <linux/init.h>
  24. #include <asm/uaccess.h>
  25. #include <linux/highmem.h>
  26. #include <linux/smp_lock.h>
  27. #include <asm/mmu_context.h>
  28. #include <linux/interrupt.h>
  29. #include <linux/completion.h>
  30. #include <linux/kernel_stat.h>
  31. #include <linux/security.h>
  32. #include <linux/notifier.h>
  33. #include <linux/profile.h>
  34. #include <linux/suspend.h>
  35. #include <linux/blkdev.h>
  36. #include <linux/delay.h>
  37. #include <linux/smp.h>
  38. #include <linux/threads.h>
  39. #include <linux/timer.h>
  40. #include <linux/rcupdate.h>
  41. #include <linux/cpu.h>
  42. #include <linux/cpuset.h>
  43. #include <linux/percpu.h>
  44. #include <linux/kthread.h>
  45. #include <linux/seq_file.h>
  46. #include <linux/syscalls.h>
  47. #include <linux/times.h>
  48. #include <linux/acct.h>
  49. #include <asm/tlb.h>
  50. #include <asm/unistd.h>
  51. /*
  52. * Convert user-nice values [ -20 ... 0 ... 19 ]
  53. * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
  54. * and back.
  55. */
  56. #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
  57. #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
  58. #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
  59. /*
  60. * 'User priority' is the nice value converted to something we
  61. * can work with better when scaling various scheduler parameters,
  62. * it's a [ 0 ... 39 ] range.
  63. */
  64. #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
  65. #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
  66. #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
  67. /*
  68. * Some helpers for converting nanosecond timing to jiffy resolution
  69. */
  70. #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
  71. #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
  72. /*
  73. * These are the 'tuning knobs' of the scheduler:
  74. *
  75. * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
  76. * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
  77. * Timeslices get refilled after they expire.
  78. */
  79. #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
  80. #define DEF_TIMESLICE (100 * HZ / 1000)
  81. #define ON_RUNQUEUE_WEIGHT 30
  82. #define CHILD_PENALTY 95
  83. #define PARENT_PENALTY 100
  84. #define EXIT_WEIGHT 3
  85. #define PRIO_BONUS_RATIO 25
  86. #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
  87. #define INTERACTIVE_DELTA 2
  88. #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
  89. #define STARVATION_LIMIT (MAX_SLEEP_AVG)
  90. #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
  91. /*
  92. * If a task is 'interactive' then we reinsert it in the active
  93. * array after it has expired its current timeslice. (it will not
  94. * continue to run immediately, it will still roundrobin with
  95. * other interactive tasks.)
  96. *
  97. * This part scales the interactivity limit depending on niceness.
  98. *
  99. * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
  100. * Here are a few examples of different nice levels:
  101. *
  102. * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
  103. * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
  104. * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
  105. * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
  106. * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
  107. *
  108. * (the X axis represents the possible -5 ... 0 ... +5 dynamic
  109. * priority range a task can explore, a value of '1' means the
  110. * task is rated interactive.)
  111. *
  112. * Ie. nice +19 tasks can never get 'interactive' enough to be
  113. * reinserted into the active array. And only heavily CPU-hog nice -20
  114. * tasks will be expired. Default nice 0 tasks are somewhere between,
  115. * it takes some effort for them to get interactive, but it's not
  116. * too hard.
  117. */
  118. #define CURRENT_BONUS(p) \
  119. (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
  120. MAX_SLEEP_AVG)
  121. #define GRANULARITY (10 * HZ / 1000 ? : 1)
  122. #ifdef CONFIG_SMP
  123. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  124. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
  125. num_online_cpus())
  126. #else
  127. #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
  128. (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
  129. #endif
  130. #define SCALE(v1,v1_max,v2_max) \
  131. (v1) * (v2_max) / (v1_max)
  132. #define DELTA(p) \
  133. (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
  134. #define TASK_INTERACTIVE(p) \
  135. ((p)->prio <= (p)->static_prio - DELTA(p))
  136. #define INTERACTIVE_SLEEP(p) \
  137. (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
  138. (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
  139. #define TASK_PREEMPTS_CURR(p, rq) \
  140. ((p)->prio < (rq)->curr->prio)
  141. /*
  142. * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
  143. * to time slice values: [800ms ... 100ms ... 5ms]
  144. *
  145. * The higher a thread's priority, the bigger timeslices
  146. * it gets during one round of execution. But even the lowest
  147. * priority thread gets MIN_TIMESLICE worth of execution time.
  148. */
  149. #define SCALE_PRIO(x, prio) \
  150. max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
  151. static unsigned int task_timeslice(task_t *p)
  152. {
  153. if (p->static_prio < NICE_TO_PRIO(0))
  154. return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
  155. else
  156. return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
  157. }
  158. #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
  159. < (long long) (sd)->cache_hot_time)
  160. /*
  161. * These are the runqueue data structures:
  162. */
  163. #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
  164. typedef struct runqueue runqueue_t;
  165. struct prio_array {
  166. unsigned int nr_active;
  167. unsigned long bitmap[BITMAP_SIZE];
  168. struct list_head queue[MAX_PRIO];
  169. };
  170. /*
  171. * This is the main, per-CPU runqueue data structure.
  172. *
  173. * Locking rule: those places that want to lock multiple runqueues
  174. * (such as the load balancing or the thread migration code), lock
  175. * acquire operations must be ordered by ascending &runqueue.
  176. */
  177. struct runqueue {
  178. spinlock_t lock;
  179. /*
  180. * nr_running and cpu_load should be in the same cacheline because
  181. * remote CPUs use both these fields when doing load calculation.
  182. */
  183. unsigned long nr_running;
  184. #ifdef CONFIG_SMP
  185. unsigned long cpu_load[3];
  186. #endif
  187. unsigned long long nr_switches;
  188. /*
  189. * This is part of a global counter where only the total sum
  190. * over all CPUs matters. A task can increase this counter on
  191. * one CPU and if it got migrated afterwards it may decrease
  192. * it on another CPU. Always updated under the runqueue lock:
  193. */
  194. unsigned long nr_uninterruptible;
  195. unsigned long expired_timestamp;
  196. unsigned long long timestamp_last_tick;
  197. task_t *curr, *idle;
  198. struct mm_struct *prev_mm;
  199. prio_array_t *active, *expired, arrays[2];
  200. int best_expired_prio;
  201. atomic_t nr_iowait;
  202. #ifdef CONFIG_SMP
  203. struct sched_domain *sd;
  204. /* For active balancing */
  205. int active_balance;
  206. int push_cpu;
  207. task_t *migration_thread;
  208. struct list_head migration_queue;
  209. #endif
  210. #ifdef CONFIG_SCHEDSTATS
  211. /* latency stats */
  212. struct sched_info rq_sched_info;
  213. /* sys_sched_yield() stats */
  214. unsigned long yld_exp_empty;
  215. unsigned long yld_act_empty;
  216. unsigned long yld_both_empty;
  217. unsigned long yld_cnt;
  218. /* schedule() stats */
  219. unsigned long sched_switch;
  220. unsigned long sched_cnt;
  221. unsigned long sched_goidle;
  222. /* try_to_wake_up() stats */
  223. unsigned long ttwu_cnt;
  224. unsigned long ttwu_local;
  225. #endif
  226. };
  227. static DEFINE_PER_CPU(struct runqueue, runqueues);
  228. /*
  229. * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
  230. * See detach_destroy_domains: synchronize_sched for details.
  231. *
  232. * The domain tree of any CPU may only be accessed from within
  233. * preempt-disabled sections.
  234. */
  235. #define for_each_domain(cpu, domain) \
  236. for (domain = rcu_dereference(cpu_rq(cpu)->sd); domain; domain = domain->parent)
  237. #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
  238. #define this_rq() (&__get_cpu_var(runqueues))
  239. #define task_rq(p) cpu_rq(task_cpu(p))
  240. #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
  241. #ifndef prepare_arch_switch
  242. # define prepare_arch_switch(next) do { } while (0)
  243. #endif
  244. #ifndef finish_arch_switch
  245. # define finish_arch_switch(prev) do { } while (0)
  246. #endif
  247. #ifndef __ARCH_WANT_UNLOCKED_CTXSW
  248. static inline int task_running(runqueue_t *rq, task_t *p)
  249. {
  250. return rq->curr == p;
  251. }
  252. static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
  253. {
  254. }
  255. static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
  256. {
  257. spin_unlock_irq(&rq->lock);
  258. }
  259. #else /* __ARCH_WANT_UNLOCKED_CTXSW */
  260. static inline int task_running(runqueue_t *rq, task_t *p)
  261. {
  262. #ifdef CONFIG_SMP
  263. return p->oncpu;
  264. #else
  265. return rq->curr == p;
  266. #endif
  267. }
  268. static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
  269. {
  270. #ifdef CONFIG_SMP
  271. /*
  272. * We can optimise this out completely for !SMP, because the
  273. * SMP rebalancing from interrupt is the only thing that cares
  274. * here.
  275. */
  276. next->oncpu = 1;
  277. #endif
  278. #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  279. spin_unlock_irq(&rq->lock);
  280. #else
  281. spin_unlock(&rq->lock);
  282. #endif
  283. }
  284. static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
  285. {
  286. #ifdef CONFIG_SMP
  287. /*
  288. * After ->oncpu is cleared, the task can be moved to a different CPU.
  289. * We must ensure this doesn't happen until the switch is completely
  290. * finished.
  291. */
  292. smp_wmb();
  293. prev->oncpu = 0;
  294. #endif
  295. #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
  296. local_irq_enable();
  297. #endif
  298. }
  299. #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
  300. /*
  301. * task_rq_lock - lock the runqueue a given task resides on and disable
  302. * interrupts. Note the ordering: we can safely lookup the task_rq without
  303. * explicitly disabling preemption.
  304. */
  305. static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
  306. __acquires(rq->lock)
  307. {
  308. struct runqueue *rq;
  309. repeat_lock_task:
  310. local_irq_save(*flags);
  311. rq = task_rq(p);
  312. spin_lock(&rq->lock);
  313. if (unlikely(rq != task_rq(p))) {
  314. spin_unlock_irqrestore(&rq->lock, *flags);
  315. goto repeat_lock_task;
  316. }
  317. return rq;
  318. }
  319. static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
  320. __releases(rq->lock)
  321. {
  322. spin_unlock_irqrestore(&rq->lock, *flags);
  323. }
  324. #ifdef CONFIG_SCHEDSTATS
  325. /*
  326. * bump this up when changing the output format or the meaning of an existing
  327. * format, so that tools can adapt (or abort)
  328. */
  329. #define SCHEDSTAT_VERSION 12
  330. static int show_schedstat(struct seq_file *seq, void *v)
  331. {
  332. int cpu;
  333. seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
  334. seq_printf(seq, "timestamp %lu\n", jiffies);
  335. for_each_online_cpu(cpu) {
  336. runqueue_t *rq = cpu_rq(cpu);
  337. #ifdef CONFIG_SMP
  338. struct sched_domain *sd;
  339. int dcnt = 0;
  340. #endif
  341. /* runqueue-specific stats */
  342. seq_printf(seq,
  343. "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
  344. cpu, rq->yld_both_empty,
  345. rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
  346. rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
  347. rq->ttwu_cnt, rq->ttwu_local,
  348. rq->rq_sched_info.cpu_time,
  349. rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
  350. seq_printf(seq, "\n");
  351. #ifdef CONFIG_SMP
  352. /* domain-specific stats */
  353. preempt_disable();
  354. for_each_domain(cpu, sd) {
  355. enum idle_type itype;
  356. char mask_str[NR_CPUS];
  357. cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
  358. seq_printf(seq, "domain%d %s", dcnt++, mask_str);
  359. for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
  360. itype++) {
  361. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
  362. sd->lb_cnt[itype],
  363. sd->lb_balanced[itype],
  364. sd->lb_failed[itype],
  365. sd->lb_imbalance[itype],
  366. sd->lb_gained[itype],
  367. sd->lb_hot_gained[itype],
  368. sd->lb_nobusyq[itype],
  369. sd->lb_nobusyg[itype]);
  370. }
  371. seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
  372. sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
  373. sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
  374. sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
  375. sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
  376. }
  377. preempt_enable();
  378. #endif
  379. }
  380. return 0;
  381. }
  382. static int schedstat_open(struct inode *inode, struct file *file)
  383. {
  384. unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
  385. char *buf = kmalloc(size, GFP_KERNEL);
  386. struct seq_file *m;
  387. int res;
  388. if (!buf)
  389. return -ENOMEM;
  390. res = single_open(file, show_schedstat, NULL);
  391. if (!res) {
  392. m = file->private_data;
  393. m->buf = buf;
  394. m->size = size;
  395. } else
  396. kfree(buf);
  397. return res;
  398. }
  399. struct file_operations proc_schedstat_operations = {
  400. .open = schedstat_open,
  401. .read = seq_read,
  402. .llseek = seq_lseek,
  403. .release = single_release,
  404. };
  405. # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
  406. # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
  407. #else /* !CONFIG_SCHEDSTATS */
  408. # define schedstat_inc(rq, field) do { } while (0)
  409. # define schedstat_add(rq, field, amt) do { } while (0)
  410. #endif
  411. /*
  412. * rq_lock - lock a given runqueue and disable interrupts.
  413. */
  414. static inline runqueue_t *this_rq_lock(void)
  415. __acquires(rq->lock)
  416. {
  417. runqueue_t *rq;
  418. local_irq_disable();
  419. rq = this_rq();
  420. spin_lock(&rq->lock);
  421. return rq;
  422. }
  423. #ifdef CONFIG_SCHEDSTATS
  424. /*
  425. * Called when a process is dequeued from the active array and given
  426. * the cpu. We should note that with the exception of interactive
  427. * tasks, the expired queue will become the active queue after the active
  428. * queue is empty, without explicitly dequeuing and requeuing tasks in the
  429. * expired queue. (Interactive tasks may be requeued directly to the
  430. * active queue, thus delaying tasks in the expired queue from running;
  431. * see scheduler_tick()).
  432. *
  433. * This function is only called from sched_info_arrive(), rather than
  434. * dequeue_task(). Even though a task may be queued and dequeued multiple
  435. * times as it is shuffled about, we're really interested in knowing how
  436. * long it was from the *first* time it was queued to the time that it
  437. * finally hit a cpu.
  438. */
  439. static inline void sched_info_dequeued(task_t *t)
  440. {
  441. t->sched_info.last_queued = 0;
  442. }
  443. /*
  444. * Called when a task finally hits the cpu. We can now calculate how
  445. * long it was waiting to run. We also note when it began so that we
  446. * can keep stats on how long its timeslice is.
  447. */
  448. static inline void sched_info_arrive(task_t *t)
  449. {
  450. unsigned long now = jiffies, diff = 0;
  451. struct runqueue *rq = task_rq(t);
  452. if (t->sched_info.last_queued)
  453. diff = now - t->sched_info.last_queued;
  454. sched_info_dequeued(t);
  455. t->sched_info.run_delay += diff;
  456. t->sched_info.last_arrival = now;
  457. t->sched_info.pcnt++;
  458. if (!rq)
  459. return;
  460. rq->rq_sched_info.run_delay += diff;
  461. rq->rq_sched_info.pcnt++;
  462. }
  463. /*
  464. * Called when a process is queued into either the active or expired
  465. * array. The time is noted and later used to determine how long we
  466. * had to wait for us to reach the cpu. Since the expired queue will
  467. * become the active queue after active queue is empty, without dequeuing
  468. * and requeuing any tasks, we are interested in queuing to either. It
  469. * is unusual but not impossible for tasks to be dequeued and immediately
  470. * requeued in the same or another array: this can happen in sched_yield(),
  471. * set_user_nice(), and even load_balance() as it moves tasks from runqueue
  472. * to runqueue.
  473. *
  474. * This function is only called from enqueue_task(), but also only updates
  475. * the timestamp if it is already not set. It's assumed that
  476. * sched_info_dequeued() will clear that stamp when appropriate.
  477. */
  478. static inline void sched_info_queued(task_t *t)
  479. {
  480. if (!t->sched_info.last_queued)
  481. t->sched_info.last_queued = jiffies;
  482. }
  483. /*
  484. * Called when a process ceases being the active-running process, either
  485. * voluntarily or involuntarily. Now we can calculate how long we ran.
  486. */
  487. static inline void sched_info_depart(task_t *t)
  488. {
  489. struct runqueue *rq = task_rq(t);
  490. unsigned long diff = jiffies - t->sched_info.last_arrival;
  491. t->sched_info.cpu_time += diff;
  492. if (rq)
  493. rq->rq_sched_info.cpu_time += diff;
  494. }
  495. /*
  496. * Called when tasks are switched involuntarily due, typically, to expiring
  497. * their time slice. (This may also be called when switching to or from
  498. * the idle task.) We are only called when prev != next.
  499. */
  500. static inline void sched_info_switch(task_t *prev, task_t *next)
  501. {
  502. struct runqueue *rq = task_rq(prev);
  503. /*
  504. * prev now departs the cpu. It's not interesting to record
  505. * stats about how efficient we were at scheduling the idle
  506. * process, however.
  507. */
  508. if (prev != rq->idle)
  509. sched_info_depart(prev);
  510. if (next != rq->idle)
  511. sched_info_arrive(next);
  512. }
  513. #else
  514. #define sched_info_queued(t) do { } while (0)
  515. #define sched_info_switch(t, next) do { } while (0)
  516. #endif /* CONFIG_SCHEDSTATS */
  517. /*
  518. * Adding/removing a task to/from a priority array:
  519. */
  520. static void dequeue_task(struct task_struct *p, prio_array_t *array)
  521. {
  522. array->nr_active--;
  523. list_del(&p->run_list);
  524. if (list_empty(array->queue + p->prio))
  525. __clear_bit(p->prio, array->bitmap);
  526. }
  527. static void enqueue_task(struct task_struct *p, prio_array_t *array)
  528. {
  529. sched_info_queued(p);
  530. list_add_tail(&p->run_list, array->queue + p->prio);
  531. __set_bit(p->prio, array->bitmap);
  532. array->nr_active++;
  533. p->array = array;
  534. }
  535. /*
  536. * Put task to the end of the run list without the overhead of dequeue
  537. * followed by enqueue.
  538. */
  539. static void requeue_task(struct task_struct *p, prio_array_t *array)
  540. {
  541. list_move_tail(&p->run_list, array->queue + p->prio);
  542. }
  543. static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
  544. {
  545. list_add(&p->run_list, array->queue + p->prio);
  546. __set_bit(p->prio, array->bitmap);
  547. array->nr_active++;
  548. p->array = array;
  549. }
  550. /*
  551. * effective_prio - return the priority that is based on the static
  552. * priority but is modified by bonuses/penalties.
  553. *
  554. * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
  555. * into the -5 ... 0 ... +5 bonus/penalty range.
  556. *
  557. * We use 25% of the full 0...39 priority range so that:
  558. *
  559. * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
  560. * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
  561. *
  562. * Both properties are important to certain workloads.
  563. */
  564. static int effective_prio(task_t *p)
  565. {
  566. int bonus, prio;
  567. if (rt_task(p))
  568. return p->prio;
  569. bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
  570. prio = p->static_prio - bonus;
  571. if (prio < MAX_RT_PRIO)
  572. prio = MAX_RT_PRIO;
  573. if (prio > MAX_PRIO-1)
  574. prio = MAX_PRIO-1;
  575. return prio;
  576. }
  577. /*
  578. * __activate_task - move a task to the runqueue.
  579. */
  580. static inline void __activate_task(task_t *p, runqueue_t *rq)
  581. {
  582. enqueue_task(p, rq->active);
  583. rq->nr_running++;
  584. }
  585. /*
  586. * __activate_idle_task - move idle task to the _front_ of runqueue.
  587. */
  588. static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
  589. {
  590. enqueue_task_head(p, rq->active);
  591. rq->nr_running++;
  592. }
  593. static int recalc_task_prio(task_t *p, unsigned long long now)
  594. {
  595. /* Caller must always ensure 'now >= p->timestamp' */
  596. unsigned long long __sleep_time = now - p->timestamp;
  597. unsigned long sleep_time;
  598. if (__sleep_time > NS_MAX_SLEEP_AVG)
  599. sleep_time = NS_MAX_SLEEP_AVG;
  600. else
  601. sleep_time = (unsigned long)__sleep_time;
  602. if (likely(sleep_time > 0)) {
  603. /*
  604. * User tasks that sleep a long time are categorised as
  605. * idle and will get just interactive status to stay active &
  606. * prevent them suddenly becoming cpu hogs and starving
  607. * other processes.
  608. */
  609. if (p->mm && p->activated != -1 &&
  610. sleep_time > INTERACTIVE_SLEEP(p)) {
  611. p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
  612. DEF_TIMESLICE);
  613. } else {
  614. /*
  615. * The lower the sleep avg a task has the more
  616. * rapidly it will rise with sleep time.
  617. */
  618. sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
  619. /*
  620. * Tasks waking from uninterruptible sleep are
  621. * limited in their sleep_avg rise as they
  622. * are likely to be waiting on I/O
  623. */
  624. if (p->activated == -1 && p->mm) {
  625. if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
  626. sleep_time = 0;
  627. else if (p->sleep_avg + sleep_time >=
  628. INTERACTIVE_SLEEP(p)) {
  629. p->sleep_avg = INTERACTIVE_SLEEP(p);
  630. sleep_time = 0;
  631. }
  632. }
  633. /*
  634. * This code gives a bonus to interactive tasks.
  635. *
  636. * The boost works by updating the 'average sleep time'
  637. * value here, based on ->timestamp. The more time a
  638. * task spends sleeping, the higher the average gets -
  639. * and the higher the priority boost gets as well.
  640. */
  641. p->sleep_avg += sleep_time;
  642. if (p->sleep_avg > NS_MAX_SLEEP_AVG)
  643. p->sleep_avg = NS_MAX_SLEEP_AVG;
  644. }
  645. }
  646. return effective_prio(p);
  647. }
  648. /*
  649. * activate_task - move a task to the runqueue and do priority recalculation
  650. *
  651. * Update all the scheduling statistics stuff. (sleep average
  652. * calculation, priority modifiers, etc.)
  653. */
  654. static void activate_task(task_t *p, runqueue_t *rq, int local)
  655. {
  656. unsigned long long now;
  657. now = sched_clock();
  658. #ifdef CONFIG_SMP
  659. if (!local) {
  660. /* Compensate for drifting sched_clock */
  661. runqueue_t *this_rq = this_rq();
  662. now = (now - this_rq->timestamp_last_tick)
  663. + rq->timestamp_last_tick;
  664. }
  665. #endif
  666. p->prio = recalc_task_prio(p, now);
  667. /*
  668. * This checks to make sure it's not an uninterruptible task
  669. * that is now waking up.
  670. */
  671. if (!p->activated) {
  672. /*
  673. * Tasks which were woken up by interrupts (ie. hw events)
  674. * are most likely of interactive nature. So we give them
  675. * the credit of extending their sleep time to the period
  676. * of time they spend on the runqueue, waiting for execution
  677. * on a CPU, first time around:
  678. */
  679. if (in_interrupt())
  680. p->activated = 2;
  681. else {
  682. /*
  683. * Normal first-time wakeups get a credit too for
  684. * on-runqueue time, but it will be weighted down:
  685. */
  686. p->activated = 1;
  687. }
  688. }
  689. p->timestamp = now;
  690. __activate_task(p, rq);
  691. }
  692. /*
  693. * deactivate_task - remove a task from the runqueue.
  694. */
  695. static void deactivate_task(struct task_struct *p, runqueue_t *rq)
  696. {
  697. rq->nr_running--;
  698. dequeue_task(p, p->array);
  699. p->array = NULL;
  700. }
  701. /*
  702. * resched_task - mark a task 'to be rescheduled now'.
  703. *
  704. * On UP this means the setting of the need_resched flag, on SMP it
  705. * might also involve a cross-CPU call to trigger the scheduler on
  706. * the target CPU.
  707. */
  708. #ifdef CONFIG_SMP
  709. static void resched_task(task_t *p)
  710. {
  711. int need_resched, nrpolling;
  712. assert_spin_locked(&task_rq(p)->lock);
  713. /* minimise the chance of sending an interrupt to poll_idle() */
  714. nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
  715. need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
  716. nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
  717. if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
  718. smp_send_reschedule(task_cpu(p));
  719. }
  720. #else
  721. static inline void resched_task(task_t *p)
  722. {
  723. set_tsk_need_resched(p);
  724. }
  725. #endif
  726. /**
  727. * task_curr - is this task currently executing on a CPU?
  728. * @p: the task in question.
  729. */
  730. inline int task_curr(const task_t *p)
  731. {
  732. return cpu_curr(task_cpu(p)) == p;
  733. }
  734. #ifdef CONFIG_SMP
  735. typedef struct {
  736. struct list_head list;
  737. task_t *task;
  738. int dest_cpu;
  739. struct completion done;
  740. } migration_req_t;
  741. /*
  742. * The task's runqueue lock must be held.
  743. * Returns true if you have to wait for migration thread.
  744. */
  745. static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
  746. {
  747. runqueue_t *rq = task_rq(p);
  748. /*
  749. * If the task is not on a runqueue (and not running), then
  750. * it is sufficient to simply update the task's cpu field.
  751. */
  752. if (!p->array && !task_running(rq, p)) {
  753. set_task_cpu(p, dest_cpu);
  754. return 0;
  755. }
  756. init_completion(&req->done);
  757. req->task = p;
  758. req->dest_cpu = dest_cpu;
  759. list_add(&req->list, &rq->migration_queue);
  760. return 1;
  761. }
  762. /*
  763. * wait_task_inactive - wait for a thread to unschedule.
  764. *
  765. * The caller must ensure that the task *will* unschedule sometime soon,
  766. * else this function might spin for a *long* time. This function can't
  767. * be called with interrupts off, or it may introduce deadlock with
  768. * smp_call_function() if an IPI is sent by the same process we are
  769. * waiting to become inactive.
  770. */
  771. void wait_task_inactive(task_t *p)
  772. {
  773. unsigned long flags;
  774. runqueue_t *rq;
  775. int preempted;
  776. repeat:
  777. rq = task_rq_lock(p, &flags);
  778. /* Must be off runqueue entirely, not preempted. */
  779. if (unlikely(p->array || task_running(rq, p))) {
  780. /* If it's preempted, we yield. It could be a while. */
  781. preempted = !task_running(rq, p);
  782. task_rq_unlock(rq, &flags);
  783. cpu_relax();
  784. if (preempted)
  785. yield();
  786. goto repeat;
  787. }
  788. task_rq_unlock(rq, &flags);
  789. }
  790. /***
  791. * kick_process - kick a running thread to enter/exit the kernel
  792. * @p: the to-be-kicked thread
  793. *
  794. * Cause a process which is running on another CPU to enter
  795. * kernel-mode, without any delay. (to get signals handled.)
  796. *
  797. * NOTE: this function doesnt have to take the runqueue lock,
  798. * because all it wants to ensure is that the remote task enters
  799. * the kernel. If the IPI races and the task has been migrated
  800. * to another CPU then no harm is done and the purpose has been
  801. * achieved as well.
  802. */
  803. void kick_process(task_t *p)
  804. {
  805. int cpu;
  806. preempt_disable();
  807. cpu = task_cpu(p);
  808. if ((cpu != smp_processor_id()) && task_curr(p))
  809. smp_send_reschedule(cpu);
  810. preempt_enable();
  811. }
  812. /*
  813. * Return a low guess at the load of a migration-source cpu.
  814. *
  815. * We want to under-estimate the load of migration sources, to
  816. * balance conservatively.
  817. */
  818. static inline unsigned long source_load(int cpu, int type)
  819. {
  820. runqueue_t *rq = cpu_rq(cpu);
  821. unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
  822. if (type == 0)
  823. return load_now;
  824. return min(rq->cpu_load[type-1], load_now);
  825. }
  826. /*
  827. * Return a high guess at the load of a migration-target cpu
  828. */
  829. static inline unsigned long target_load(int cpu, int type)
  830. {
  831. runqueue_t *rq = cpu_rq(cpu);
  832. unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
  833. if (type == 0)
  834. return load_now;
  835. return max(rq->cpu_load[type-1], load_now);
  836. }
  837. /*
  838. * find_idlest_group finds and returns the least busy CPU group within the
  839. * domain.
  840. */
  841. static struct sched_group *
  842. find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
  843. {
  844. struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
  845. unsigned long min_load = ULONG_MAX, this_load = 0;
  846. int load_idx = sd->forkexec_idx;
  847. int imbalance = 100 + (sd->imbalance_pct-100)/2;
  848. do {
  849. unsigned long load, avg_load;
  850. int local_group;
  851. int i;
  852. /* Skip over this group if it has no CPUs allowed */
  853. if (!cpus_intersects(group->cpumask, p->cpus_allowed))
  854. goto nextgroup;
  855. local_group = cpu_isset(this_cpu, group->cpumask);
  856. /* Tally up the load of all CPUs in the group */
  857. avg_load = 0;
  858. for_each_cpu_mask(i, group->cpumask) {
  859. /* Bias balancing toward cpus of our domain */
  860. if (local_group)
  861. load = source_load(i, load_idx);
  862. else
  863. load = target_load(i, load_idx);
  864. avg_load += load;
  865. }
  866. /* Adjust by relative CPU power of the group */
  867. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  868. if (local_group) {
  869. this_load = avg_load;
  870. this = group;
  871. } else if (avg_load < min_load) {
  872. min_load = avg_load;
  873. idlest = group;
  874. }
  875. nextgroup:
  876. group = group->next;
  877. } while (group != sd->groups);
  878. if (!idlest || 100*this_load < imbalance*min_load)
  879. return NULL;
  880. return idlest;
  881. }
  882. /*
  883. * find_idlest_queue - find the idlest runqueue among the cpus in group.
  884. */
  885. static int
  886. find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
  887. {
  888. cpumask_t tmp;
  889. unsigned long load, min_load = ULONG_MAX;
  890. int idlest = -1;
  891. int i;
  892. /* Traverse only the allowed CPUs */
  893. cpus_and(tmp, group->cpumask, p->cpus_allowed);
  894. for_each_cpu_mask(i, tmp) {
  895. load = source_load(i, 0);
  896. if (load < min_load || (load == min_load && i == this_cpu)) {
  897. min_load = load;
  898. idlest = i;
  899. }
  900. }
  901. return idlest;
  902. }
  903. /*
  904. * sched_balance_self: balance the current task (running on cpu) in domains
  905. * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
  906. * SD_BALANCE_EXEC.
  907. *
  908. * Balance, ie. select the least loaded group.
  909. *
  910. * Returns the target CPU number, or the same CPU if no balancing is needed.
  911. *
  912. * preempt must be disabled.
  913. */
  914. static int sched_balance_self(int cpu, int flag)
  915. {
  916. struct task_struct *t = current;
  917. struct sched_domain *tmp, *sd = NULL;
  918. for_each_domain(cpu, tmp)
  919. if (tmp->flags & flag)
  920. sd = tmp;
  921. while (sd) {
  922. cpumask_t span;
  923. struct sched_group *group;
  924. int new_cpu;
  925. int weight;
  926. span = sd->span;
  927. group = find_idlest_group(sd, t, cpu);
  928. if (!group)
  929. goto nextlevel;
  930. new_cpu = find_idlest_cpu(group, t, cpu);
  931. if (new_cpu == -1 || new_cpu == cpu)
  932. goto nextlevel;
  933. /* Now try balancing at a lower domain level */
  934. cpu = new_cpu;
  935. nextlevel:
  936. sd = NULL;
  937. weight = cpus_weight(span);
  938. for_each_domain(cpu, tmp) {
  939. if (weight <= cpus_weight(tmp->span))
  940. break;
  941. if (tmp->flags & flag)
  942. sd = tmp;
  943. }
  944. /* while loop will break here if sd == NULL */
  945. }
  946. return cpu;
  947. }
  948. #endif /* CONFIG_SMP */
  949. /*
  950. * wake_idle() will wake a task on an idle cpu if task->cpu is
  951. * not idle and an idle cpu is available. The span of cpus to
  952. * search starts with cpus closest then further out as needed,
  953. * so we always favor a closer, idle cpu.
  954. *
  955. * Returns the CPU we should wake onto.
  956. */
  957. #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
  958. static int wake_idle(int cpu, task_t *p)
  959. {
  960. cpumask_t tmp;
  961. struct sched_domain *sd;
  962. int i;
  963. if (idle_cpu(cpu))
  964. return cpu;
  965. for_each_domain(cpu, sd) {
  966. if (sd->flags & SD_WAKE_IDLE) {
  967. cpus_and(tmp, sd->span, p->cpus_allowed);
  968. for_each_cpu_mask(i, tmp) {
  969. if (idle_cpu(i))
  970. return i;
  971. }
  972. }
  973. else
  974. break;
  975. }
  976. return cpu;
  977. }
  978. #else
  979. static inline int wake_idle(int cpu, task_t *p)
  980. {
  981. return cpu;
  982. }
  983. #endif
  984. /***
  985. * try_to_wake_up - wake up a thread
  986. * @p: the to-be-woken-up thread
  987. * @state: the mask of task states that can be woken
  988. * @sync: do a synchronous wakeup?
  989. *
  990. * Put it on the run-queue if it's not already there. The "current"
  991. * thread is always on the run-queue (except when the actual
  992. * re-schedule is in progress), and as such you're allowed to do
  993. * the simpler "current->state = TASK_RUNNING" to mark yourself
  994. * runnable without the overhead of this.
  995. *
  996. * returns failure only if the task is already active.
  997. */
  998. static int try_to_wake_up(task_t *p, unsigned int state, int sync)
  999. {
  1000. int cpu, this_cpu, success = 0;
  1001. unsigned long flags;
  1002. long old_state;
  1003. runqueue_t *rq;
  1004. #ifdef CONFIG_SMP
  1005. unsigned long load, this_load;
  1006. struct sched_domain *sd, *this_sd = NULL;
  1007. int new_cpu;
  1008. #endif
  1009. rq = task_rq_lock(p, &flags);
  1010. old_state = p->state;
  1011. if (!(old_state & state))
  1012. goto out;
  1013. if (p->array)
  1014. goto out_running;
  1015. cpu = task_cpu(p);
  1016. this_cpu = smp_processor_id();
  1017. #ifdef CONFIG_SMP
  1018. if (unlikely(task_running(rq, p)))
  1019. goto out_activate;
  1020. new_cpu = cpu;
  1021. schedstat_inc(rq, ttwu_cnt);
  1022. if (cpu == this_cpu) {
  1023. schedstat_inc(rq, ttwu_local);
  1024. goto out_set_cpu;
  1025. }
  1026. for_each_domain(this_cpu, sd) {
  1027. if (cpu_isset(cpu, sd->span)) {
  1028. schedstat_inc(sd, ttwu_wake_remote);
  1029. this_sd = sd;
  1030. break;
  1031. }
  1032. }
  1033. if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
  1034. goto out_set_cpu;
  1035. /*
  1036. * Check for affine wakeup and passive balancing possibilities.
  1037. */
  1038. if (this_sd) {
  1039. int idx = this_sd->wake_idx;
  1040. unsigned int imbalance;
  1041. imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
  1042. load = source_load(cpu, idx);
  1043. this_load = target_load(this_cpu, idx);
  1044. new_cpu = this_cpu; /* Wake to this CPU if we can */
  1045. if (this_sd->flags & SD_WAKE_AFFINE) {
  1046. unsigned long tl = this_load;
  1047. /*
  1048. * If sync wakeup then subtract the (maximum possible)
  1049. * effect of the currently running task from the load
  1050. * of the current CPU:
  1051. */
  1052. if (sync)
  1053. tl -= SCHED_LOAD_SCALE;
  1054. if ((tl <= load &&
  1055. tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
  1056. 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
  1057. /*
  1058. * This domain has SD_WAKE_AFFINE and
  1059. * p is cache cold in this domain, and
  1060. * there is no bad imbalance.
  1061. */
  1062. schedstat_inc(this_sd, ttwu_move_affine);
  1063. goto out_set_cpu;
  1064. }
  1065. }
  1066. /*
  1067. * Start passive balancing when half the imbalance_pct
  1068. * limit is reached.
  1069. */
  1070. if (this_sd->flags & SD_WAKE_BALANCE) {
  1071. if (imbalance*this_load <= 100*load) {
  1072. schedstat_inc(this_sd, ttwu_move_balance);
  1073. goto out_set_cpu;
  1074. }
  1075. }
  1076. }
  1077. new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
  1078. out_set_cpu:
  1079. new_cpu = wake_idle(new_cpu, p);
  1080. if (new_cpu != cpu) {
  1081. set_task_cpu(p, new_cpu);
  1082. task_rq_unlock(rq, &flags);
  1083. /* might preempt at this point */
  1084. rq = task_rq_lock(p, &flags);
  1085. old_state = p->state;
  1086. if (!(old_state & state))
  1087. goto out;
  1088. if (p->array)
  1089. goto out_running;
  1090. this_cpu = smp_processor_id();
  1091. cpu = task_cpu(p);
  1092. }
  1093. out_activate:
  1094. #endif /* CONFIG_SMP */
  1095. if (old_state == TASK_UNINTERRUPTIBLE) {
  1096. rq->nr_uninterruptible--;
  1097. /*
  1098. * Tasks on involuntary sleep don't earn
  1099. * sleep_avg beyond just interactive state.
  1100. */
  1101. p->activated = -1;
  1102. }
  1103. /*
  1104. * Tasks that have marked their sleep as noninteractive get
  1105. * woken up without updating their sleep average. (i.e. their
  1106. * sleep is handled in a priority-neutral manner, no priority
  1107. * boost and no penalty.)
  1108. */
  1109. if (old_state & TASK_NONINTERACTIVE)
  1110. __activate_task(p, rq);
  1111. else
  1112. activate_task(p, rq, cpu == this_cpu);
  1113. /*
  1114. * Sync wakeups (i.e. those types of wakeups where the waker
  1115. * has indicated that it will leave the CPU in short order)
  1116. * don't trigger a preemption, if the woken up task will run on
  1117. * this cpu. (in this case the 'I will reschedule' promise of
  1118. * the waker guarantees that the freshly woken up task is going
  1119. * to be considered on this CPU.)
  1120. */
  1121. if (!sync || cpu != this_cpu) {
  1122. if (TASK_PREEMPTS_CURR(p, rq))
  1123. resched_task(rq->curr);
  1124. }
  1125. success = 1;
  1126. out_running:
  1127. p->state = TASK_RUNNING;
  1128. out:
  1129. task_rq_unlock(rq, &flags);
  1130. return success;
  1131. }
  1132. int fastcall wake_up_process(task_t *p)
  1133. {
  1134. return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
  1135. TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
  1136. }
  1137. EXPORT_SYMBOL(wake_up_process);
  1138. int fastcall wake_up_state(task_t *p, unsigned int state)
  1139. {
  1140. return try_to_wake_up(p, state, 0);
  1141. }
  1142. /*
  1143. * Perform scheduler related setup for a newly forked process p.
  1144. * p is forked by current.
  1145. */
  1146. void fastcall sched_fork(task_t *p, int clone_flags)
  1147. {
  1148. int cpu = get_cpu();
  1149. #ifdef CONFIG_SMP
  1150. cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
  1151. #endif
  1152. set_task_cpu(p, cpu);
  1153. /*
  1154. * We mark the process as running here, but have not actually
  1155. * inserted it onto the runqueue yet. This guarantees that
  1156. * nobody will actually run it, and a signal or other external
  1157. * event cannot wake it up and insert it on the runqueue either.
  1158. */
  1159. p->state = TASK_RUNNING;
  1160. INIT_LIST_HEAD(&p->run_list);
  1161. p->array = NULL;
  1162. #ifdef CONFIG_SCHEDSTATS
  1163. memset(&p->sched_info, 0, sizeof(p->sched_info));
  1164. #endif
  1165. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  1166. p->oncpu = 0;
  1167. #endif
  1168. #ifdef CONFIG_PREEMPT
  1169. /* Want to start with kernel preemption disabled. */
  1170. p->thread_info->preempt_count = 1;
  1171. #endif
  1172. /*
  1173. * Share the timeslice between parent and child, thus the
  1174. * total amount of pending timeslices in the system doesn't change,
  1175. * resulting in more scheduling fairness.
  1176. */
  1177. local_irq_disable();
  1178. p->time_slice = (current->time_slice + 1) >> 1;
  1179. /*
  1180. * The remainder of the first timeslice might be recovered by
  1181. * the parent if the child exits early enough.
  1182. */
  1183. p->first_time_slice = 1;
  1184. current->time_slice >>= 1;
  1185. p->timestamp = sched_clock();
  1186. if (unlikely(!current->time_slice)) {
  1187. /*
  1188. * This case is rare, it happens when the parent has only
  1189. * a single jiffy left from its timeslice. Taking the
  1190. * runqueue lock is not a problem.
  1191. */
  1192. current->time_slice = 1;
  1193. scheduler_tick();
  1194. }
  1195. local_irq_enable();
  1196. put_cpu();
  1197. }
  1198. /*
  1199. * wake_up_new_task - wake up a newly created task for the first time.
  1200. *
  1201. * This function will do some initial scheduler statistics housekeeping
  1202. * that must be done for every newly created context, then puts the task
  1203. * on the runqueue and wakes it.
  1204. */
  1205. void fastcall wake_up_new_task(task_t *p, unsigned long clone_flags)
  1206. {
  1207. unsigned long flags;
  1208. int this_cpu, cpu;
  1209. runqueue_t *rq, *this_rq;
  1210. rq = task_rq_lock(p, &flags);
  1211. BUG_ON(p->state != TASK_RUNNING);
  1212. this_cpu = smp_processor_id();
  1213. cpu = task_cpu(p);
  1214. /*
  1215. * We decrease the sleep average of forking parents
  1216. * and children as well, to keep max-interactive tasks
  1217. * from forking tasks that are max-interactive. The parent
  1218. * (current) is done further down, under its lock.
  1219. */
  1220. p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
  1221. CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1222. p->prio = effective_prio(p);
  1223. if (likely(cpu == this_cpu)) {
  1224. if (!(clone_flags & CLONE_VM)) {
  1225. /*
  1226. * The VM isn't cloned, so we're in a good position to
  1227. * do child-runs-first in anticipation of an exec. This
  1228. * usually avoids a lot of COW overhead.
  1229. */
  1230. if (unlikely(!current->array))
  1231. __activate_task(p, rq);
  1232. else {
  1233. p->prio = current->prio;
  1234. list_add_tail(&p->run_list, &current->run_list);
  1235. p->array = current->array;
  1236. p->array->nr_active++;
  1237. rq->nr_running++;
  1238. }
  1239. set_need_resched();
  1240. } else
  1241. /* Run child last */
  1242. __activate_task(p, rq);
  1243. /*
  1244. * We skip the following code due to cpu == this_cpu
  1245. *
  1246. * task_rq_unlock(rq, &flags);
  1247. * this_rq = task_rq_lock(current, &flags);
  1248. */
  1249. this_rq = rq;
  1250. } else {
  1251. this_rq = cpu_rq(this_cpu);
  1252. /*
  1253. * Not the local CPU - must adjust timestamp. This should
  1254. * get optimised away in the !CONFIG_SMP case.
  1255. */
  1256. p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
  1257. + rq->timestamp_last_tick;
  1258. __activate_task(p, rq);
  1259. if (TASK_PREEMPTS_CURR(p, rq))
  1260. resched_task(rq->curr);
  1261. /*
  1262. * Parent and child are on different CPUs, now get the
  1263. * parent runqueue to update the parent's ->sleep_avg:
  1264. */
  1265. task_rq_unlock(rq, &flags);
  1266. this_rq = task_rq_lock(current, &flags);
  1267. }
  1268. current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
  1269. PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
  1270. task_rq_unlock(this_rq, &flags);
  1271. }
  1272. /*
  1273. * Potentially available exiting-child timeslices are
  1274. * retrieved here - this way the parent does not get
  1275. * penalized for creating too many threads.
  1276. *
  1277. * (this cannot be used to 'generate' timeslices
  1278. * artificially, because any timeslice recovered here
  1279. * was given away by the parent in the first place.)
  1280. */
  1281. void fastcall sched_exit(task_t *p)
  1282. {
  1283. unsigned long flags;
  1284. runqueue_t *rq;
  1285. /*
  1286. * If the child was a (relative-) CPU hog then decrease
  1287. * the sleep_avg of the parent as well.
  1288. */
  1289. rq = task_rq_lock(p->parent, &flags);
  1290. if (p->first_time_slice) {
  1291. p->parent->time_slice += p->time_slice;
  1292. if (unlikely(p->parent->time_slice > task_timeslice(p)))
  1293. p->parent->time_slice = task_timeslice(p);
  1294. }
  1295. if (p->sleep_avg < p->parent->sleep_avg)
  1296. p->parent->sleep_avg = p->parent->sleep_avg /
  1297. (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
  1298. (EXIT_WEIGHT + 1);
  1299. task_rq_unlock(rq, &flags);
  1300. }
  1301. /**
  1302. * prepare_task_switch - prepare to switch tasks
  1303. * @rq: the runqueue preparing to switch
  1304. * @next: the task we are going to switch to.
  1305. *
  1306. * This is called with the rq lock held and interrupts off. It must
  1307. * be paired with a subsequent finish_task_switch after the context
  1308. * switch.
  1309. *
  1310. * prepare_task_switch sets up locking and calls architecture specific
  1311. * hooks.
  1312. */
  1313. static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
  1314. {
  1315. prepare_lock_switch(rq, next);
  1316. prepare_arch_switch(next);
  1317. }
  1318. /**
  1319. * finish_task_switch - clean up after a task-switch
  1320. * @rq: runqueue associated with task-switch
  1321. * @prev: the thread we just switched away from.
  1322. *
  1323. * finish_task_switch must be called after the context switch, paired
  1324. * with a prepare_task_switch call before the context switch.
  1325. * finish_task_switch will reconcile locking set up by prepare_task_switch,
  1326. * and do any other architecture-specific cleanup actions.
  1327. *
  1328. * Note that we may have delayed dropping an mm in context_switch(). If
  1329. * so, we finish that here outside of the runqueue lock. (Doing it
  1330. * with the lock held can cause deadlocks; see schedule() for
  1331. * details.)
  1332. */
  1333. static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
  1334. __releases(rq->lock)
  1335. {
  1336. struct mm_struct *mm = rq->prev_mm;
  1337. unsigned long prev_task_flags;
  1338. rq->prev_mm = NULL;
  1339. /*
  1340. * A task struct has one reference for the use as "current".
  1341. * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
  1342. * calls schedule one last time. The schedule call will never return,
  1343. * and the scheduled task must drop that reference.
  1344. * The test for EXIT_ZOMBIE must occur while the runqueue locks are
  1345. * still held, otherwise prev could be scheduled on another cpu, die
  1346. * there before we look at prev->state, and then the reference would
  1347. * be dropped twice.
  1348. * Manfred Spraul <manfred@colorfullife.com>
  1349. */
  1350. prev_task_flags = prev->flags;
  1351. #ifdef CONFIG_DEBUG_SPINLOCK
  1352. /* this is a valid case when another task releases the spinlock */
  1353. rq->lock.owner = current;
  1354. #endif
  1355. finish_arch_switch(prev);
  1356. finish_lock_switch(rq, prev);
  1357. if (mm)
  1358. mmdrop(mm);
  1359. if (unlikely(prev_task_flags & PF_DEAD))
  1360. put_task_struct(prev);
  1361. }
  1362. /**
  1363. * schedule_tail - first thing a freshly forked thread must call.
  1364. * @prev: the thread we just switched away from.
  1365. */
  1366. asmlinkage void schedule_tail(task_t *prev)
  1367. __releases(rq->lock)
  1368. {
  1369. runqueue_t *rq = this_rq();
  1370. finish_task_switch(rq, prev);
  1371. #ifdef __ARCH_WANT_UNLOCKED_CTXSW
  1372. /* In this case, finish_task_switch does not reenable preemption */
  1373. preempt_enable();
  1374. #endif
  1375. if (current->set_child_tid)
  1376. put_user(current->pid, current->set_child_tid);
  1377. }
  1378. /*
  1379. * context_switch - switch to the new MM and the new
  1380. * thread's register state.
  1381. */
  1382. static inline
  1383. task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
  1384. {
  1385. struct mm_struct *mm = next->mm;
  1386. struct mm_struct *oldmm = prev->active_mm;
  1387. if (unlikely(!mm)) {
  1388. next->active_mm = oldmm;
  1389. atomic_inc(&oldmm->mm_count);
  1390. enter_lazy_tlb(oldmm, next);
  1391. } else
  1392. switch_mm(oldmm, mm, next);
  1393. if (unlikely(!prev->mm)) {
  1394. prev->active_mm = NULL;
  1395. WARN_ON(rq->prev_mm);
  1396. rq->prev_mm = oldmm;
  1397. }
  1398. /* Here we just switch the register state and the stack. */
  1399. switch_to(prev, next, prev);
  1400. return prev;
  1401. }
  1402. /*
  1403. * nr_running, nr_uninterruptible and nr_context_switches:
  1404. *
  1405. * externally visible scheduler statistics: current number of runnable
  1406. * threads, current number of uninterruptible-sleeping threads, total
  1407. * number of context switches performed since bootup.
  1408. */
  1409. unsigned long nr_running(void)
  1410. {
  1411. unsigned long i, sum = 0;
  1412. for_each_online_cpu(i)
  1413. sum += cpu_rq(i)->nr_running;
  1414. return sum;
  1415. }
  1416. unsigned long nr_uninterruptible(void)
  1417. {
  1418. unsigned long i, sum = 0;
  1419. for_each_cpu(i)
  1420. sum += cpu_rq(i)->nr_uninterruptible;
  1421. /*
  1422. * Since we read the counters lockless, it might be slightly
  1423. * inaccurate. Do not allow it to go below zero though:
  1424. */
  1425. if (unlikely((long)sum < 0))
  1426. sum = 0;
  1427. return sum;
  1428. }
  1429. unsigned long long nr_context_switches(void)
  1430. {
  1431. unsigned long long i, sum = 0;
  1432. for_each_cpu(i)
  1433. sum += cpu_rq(i)->nr_switches;
  1434. return sum;
  1435. }
  1436. unsigned long nr_iowait(void)
  1437. {
  1438. unsigned long i, sum = 0;
  1439. for_each_cpu(i)
  1440. sum += atomic_read(&cpu_rq(i)->nr_iowait);
  1441. return sum;
  1442. }
  1443. #ifdef CONFIG_SMP
  1444. /*
  1445. * double_rq_lock - safely lock two runqueues
  1446. *
  1447. * Note this does not disable interrupts like task_rq_lock,
  1448. * you need to do so manually before calling.
  1449. */
  1450. static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
  1451. __acquires(rq1->lock)
  1452. __acquires(rq2->lock)
  1453. {
  1454. if (rq1 == rq2) {
  1455. spin_lock(&rq1->lock);
  1456. __acquire(rq2->lock); /* Fake it out ;) */
  1457. } else {
  1458. if (rq1 < rq2) {
  1459. spin_lock(&rq1->lock);
  1460. spin_lock(&rq2->lock);
  1461. } else {
  1462. spin_lock(&rq2->lock);
  1463. spin_lock(&rq1->lock);
  1464. }
  1465. }
  1466. }
  1467. /*
  1468. * double_rq_unlock - safely unlock two runqueues
  1469. *
  1470. * Note this does not restore interrupts like task_rq_unlock,
  1471. * you need to do so manually after calling.
  1472. */
  1473. static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
  1474. __releases(rq1->lock)
  1475. __releases(rq2->lock)
  1476. {
  1477. spin_unlock(&rq1->lock);
  1478. if (rq1 != rq2)
  1479. spin_unlock(&rq2->lock);
  1480. else
  1481. __release(rq2->lock);
  1482. }
  1483. /*
  1484. * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
  1485. */
  1486. static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
  1487. __releases(this_rq->lock)
  1488. __acquires(busiest->lock)
  1489. __acquires(this_rq->lock)
  1490. {
  1491. if (unlikely(!spin_trylock(&busiest->lock))) {
  1492. if (busiest < this_rq) {
  1493. spin_unlock(&this_rq->lock);
  1494. spin_lock(&busiest->lock);
  1495. spin_lock(&this_rq->lock);
  1496. } else
  1497. spin_lock(&busiest->lock);
  1498. }
  1499. }
  1500. /*
  1501. * If dest_cpu is allowed for this process, migrate the task to it.
  1502. * This is accomplished by forcing the cpu_allowed mask to only
  1503. * allow dest_cpu, which will force the cpu onto dest_cpu. Then
  1504. * the cpu_allowed mask is restored.
  1505. */
  1506. static void sched_migrate_task(task_t *p, int dest_cpu)
  1507. {
  1508. migration_req_t req;
  1509. runqueue_t *rq;
  1510. unsigned long flags;
  1511. rq = task_rq_lock(p, &flags);
  1512. if (!cpu_isset(dest_cpu, p->cpus_allowed)
  1513. || unlikely(cpu_is_offline(dest_cpu)))
  1514. goto out;
  1515. /* force the process onto the specified CPU */
  1516. if (migrate_task(p, dest_cpu, &req)) {
  1517. /* Need to wait for migration thread (might exit: take ref). */
  1518. struct task_struct *mt = rq->migration_thread;
  1519. get_task_struct(mt);
  1520. task_rq_unlock(rq, &flags);
  1521. wake_up_process(mt);
  1522. put_task_struct(mt);
  1523. wait_for_completion(&req.done);
  1524. return;
  1525. }
  1526. out:
  1527. task_rq_unlock(rq, &flags);
  1528. }
  1529. /*
  1530. * sched_exec - execve() is a valuable balancing opportunity, because at
  1531. * this point the task has the smallest effective memory and cache footprint.
  1532. */
  1533. void sched_exec(void)
  1534. {
  1535. int new_cpu, this_cpu = get_cpu();
  1536. new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
  1537. put_cpu();
  1538. if (new_cpu != this_cpu)
  1539. sched_migrate_task(current, new_cpu);
  1540. }
  1541. /*
  1542. * pull_task - move a task from a remote runqueue to the local runqueue.
  1543. * Both runqueues must be locked.
  1544. */
  1545. static inline
  1546. void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
  1547. runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
  1548. {
  1549. dequeue_task(p, src_array);
  1550. src_rq->nr_running--;
  1551. set_task_cpu(p, this_cpu);
  1552. this_rq->nr_running++;
  1553. enqueue_task(p, this_array);
  1554. p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
  1555. + this_rq->timestamp_last_tick;
  1556. /*
  1557. * Note that idle threads have a prio of MAX_PRIO, for this test
  1558. * to be always true for them.
  1559. */
  1560. if (TASK_PREEMPTS_CURR(p, this_rq))
  1561. resched_task(this_rq->curr);
  1562. }
  1563. /*
  1564. * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
  1565. */
  1566. static inline
  1567. int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
  1568. struct sched_domain *sd, enum idle_type idle,
  1569. int *all_pinned)
  1570. {
  1571. /*
  1572. * We do not migrate tasks that are:
  1573. * 1) running (obviously), or
  1574. * 2) cannot be migrated to this CPU due to cpus_allowed, or
  1575. * 3) are cache-hot on their current CPU.
  1576. */
  1577. if (!cpu_isset(this_cpu, p->cpus_allowed))
  1578. return 0;
  1579. *all_pinned = 0;
  1580. if (task_running(rq, p))
  1581. return 0;
  1582. /*
  1583. * Aggressive migration if:
  1584. * 1) task is cache cold, or
  1585. * 2) too many balance attempts have failed.
  1586. */
  1587. if (sd->nr_balance_failed > sd->cache_nice_tries)
  1588. return 1;
  1589. if (task_hot(p, rq->timestamp_last_tick, sd))
  1590. return 0;
  1591. return 1;
  1592. }
  1593. /*
  1594. * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
  1595. * as part of a balancing operation within "domain". Returns the number of
  1596. * tasks moved.
  1597. *
  1598. * Called with both runqueues locked.
  1599. */
  1600. static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
  1601. unsigned long max_nr_move, struct sched_domain *sd,
  1602. enum idle_type idle, int *all_pinned)
  1603. {
  1604. prio_array_t *array, *dst_array;
  1605. struct list_head *head, *curr;
  1606. int idx, pulled = 0, pinned = 0;
  1607. task_t *tmp;
  1608. if (max_nr_move == 0)
  1609. goto out;
  1610. pinned = 1;
  1611. /*
  1612. * We first consider expired tasks. Those will likely not be
  1613. * executed in the near future, and they are most likely to
  1614. * be cache-cold, thus switching CPUs has the least effect
  1615. * on them.
  1616. */
  1617. if (busiest->expired->nr_active) {
  1618. array = busiest->expired;
  1619. dst_array = this_rq->expired;
  1620. } else {
  1621. array = busiest->active;
  1622. dst_array = this_rq->active;
  1623. }
  1624. new_array:
  1625. /* Start searching at priority 0: */
  1626. idx = 0;
  1627. skip_bitmap:
  1628. if (!idx)
  1629. idx = sched_find_first_bit(array->bitmap);
  1630. else
  1631. idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
  1632. if (idx >= MAX_PRIO) {
  1633. if (array == busiest->expired && busiest->active->nr_active) {
  1634. array = busiest->active;
  1635. dst_array = this_rq->active;
  1636. goto new_array;
  1637. }
  1638. goto out;
  1639. }
  1640. head = array->queue + idx;
  1641. curr = head->prev;
  1642. skip_queue:
  1643. tmp = list_entry(curr, task_t, run_list);
  1644. curr = curr->prev;
  1645. if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
  1646. if (curr != head)
  1647. goto skip_queue;
  1648. idx++;
  1649. goto skip_bitmap;
  1650. }
  1651. #ifdef CONFIG_SCHEDSTATS
  1652. if (task_hot(tmp, busiest->timestamp_last_tick, sd))
  1653. schedstat_inc(sd, lb_hot_gained[idle]);
  1654. #endif
  1655. pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
  1656. pulled++;
  1657. /* We only want to steal up to the prescribed number of tasks. */
  1658. if (pulled < max_nr_move) {
  1659. if (curr != head)
  1660. goto skip_queue;
  1661. idx++;
  1662. goto skip_bitmap;
  1663. }
  1664. out:
  1665. /*
  1666. * Right now, this is the only place pull_task() is called,
  1667. * so we can safely collect pull_task() stats here rather than
  1668. * inside pull_task().
  1669. */
  1670. schedstat_add(sd, lb_gained[idle], pulled);
  1671. if (all_pinned)
  1672. *all_pinned = pinned;
  1673. return pulled;
  1674. }
  1675. /*
  1676. * find_busiest_group finds and returns the busiest CPU group within the
  1677. * domain. It calculates and returns the number of tasks which should be
  1678. * moved to restore balance via the imbalance parameter.
  1679. */
  1680. static struct sched_group *
  1681. find_busiest_group(struct sched_domain *sd, int this_cpu,
  1682. unsigned long *imbalance, enum idle_type idle, int *sd_idle)
  1683. {
  1684. struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
  1685. unsigned long max_load, avg_load, total_load, this_load, total_pwr;
  1686. int load_idx;
  1687. max_load = this_load = total_load = total_pwr = 0;
  1688. if (idle == NOT_IDLE)
  1689. load_idx = sd->busy_idx;
  1690. else if (idle == NEWLY_IDLE)
  1691. load_idx = sd->newidle_idx;
  1692. else
  1693. load_idx = sd->idle_idx;
  1694. do {
  1695. unsigned long load;
  1696. int local_group;
  1697. int i;
  1698. local_group = cpu_isset(this_cpu, group->cpumask);
  1699. /* Tally up the load of all CPUs in the group */
  1700. avg_load = 0;
  1701. for_each_cpu_mask(i, group->cpumask) {
  1702. if (*sd_idle && !idle_cpu(i))
  1703. *sd_idle = 0;
  1704. /* Bias balancing toward cpus of our domain */
  1705. if (local_group)
  1706. load = target_load(i, load_idx);
  1707. else
  1708. load = source_load(i, load_idx);
  1709. avg_load += load;
  1710. }
  1711. total_load += avg_load;
  1712. total_pwr += group->cpu_power;
  1713. /* Adjust by relative CPU power of the group */
  1714. avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
  1715. if (local_group) {
  1716. this_load = avg_load;
  1717. this = group;
  1718. } else if (avg_load > max_load) {
  1719. max_load = avg_load;
  1720. busiest = group;
  1721. }
  1722. group = group->next;
  1723. } while (group != sd->groups);
  1724. if (!busiest || this_load >= max_load)
  1725. goto out_balanced;
  1726. avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
  1727. if (this_load >= avg_load ||
  1728. 100*max_load <= sd->imbalance_pct*this_load)
  1729. goto out_balanced;
  1730. /*
  1731. * We're trying to get all the cpus to the average_load, so we don't
  1732. * want to push ourselves above the average load, nor do we wish to
  1733. * reduce the max loaded cpu below the average load, as either of these
  1734. * actions would just result in more rebalancing later, and ping-pong
  1735. * tasks around. Thus we look for the minimum possible imbalance.
  1736. * Negative imbalances (*we* are more loaded than anyone else) will
  1737. * be counted as no imbalance for these purposes -- we can't fix that
  1738. * by pulling tasks to us. Be careful of negative numbers as they'll
  1739. * appear as very large values with unsigned longs.
  1740. */
  1741. /* How much load to actually move to equalise the imbalance */
  1742. *imbalance = min((max_load - avg_load) * busiest->cpu_power,
  1743. (avg_load - this_load) * this->cpu_power)
  1744. / SCHED_LOAD_SCALE;
  1745. if (*imbalance < SCHED_LOAD_SCALE) {
  1746. unsigned long pwr_now = 0, pwr_move = 0;
  1747. unsigned long tmp;
  1748. if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
  1749. *imbalance = 1;
  1750. return busiest;
  1751. }
  1752. /*
  1753. * OK, we don't have enough imbalance to justify moving tasks,
  1754. * however we may be able to increase total CPU power used by
  1755. * moving them.
  1756. */
  1757. pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
  1758. pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
  1759. pwr_now /= SCHED_LOAD_SCALE;
  1760. /* Amount of load we'd subtract */
  1761. tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
  1762. if (max_load > tmp)
  1763. pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
  1764. max_load - tmp);
  1765. /* Amount of load we'd add */
  1766. if (max_load*busiest->cpu_power <
  1767. SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
  1768. tmp = max_load*busiest->cpu_power/this->cpu_power;
  1769. else
  1770. tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
  1771. pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
  1772. pwr_move /= SCHED_LOAD_SCALE;
  1773. /* Move if we gain throughput */
  1774. if (pwr_move <= pwr_now)
  1775. goto out_balanced;
  1776. *imbalance = 1;
  1777. return busiest;
  1778. }
  1779. /* Get rid of the scaling factor, rounding down as we divide */
  1780. *imbalance = *imbalance / SCHED_LOAD_SCALE;
  1781. return busiest;
  1782. out_balanced:
  1783. *imbalance = 0;
  1784. return NULL;
  1785. }
  1786. /*
  1787. * find_busiest_queue - find the busiest runqueue among the cpus in group.
  1788. */
  1789. static runqueue_t *find_busiest_queue(struct sched_group *group)
  1790. {
  1791. unsigned long load, max_load = 0;
  1792. runqueue_t *busiest = NULL;
  1793. int i;
  1794. for_each_cpu_mask(i, group->cpumask) {
  1795. load = source_load(i, 0);
  1796. if (load > max_load) {
  1797. max_load = load;
  1798. busiest = cpu_rq(i);
  1799. }
  1800. }
  1801. return busiest;
  1802. }
  1803. /*
  1804. * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
  1805. * so long as it is large enough.
  1806. */
  1807. #define MAX_PINNED_INTERVAL 512
  1808. /*
  1809. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  1810. * tasks if there is an imbalance.
  1811. *
  1812. * Called with this_rq unlocked.
  1813. */
  1814. static int load_balance(int this_cpu, runqueue_t *this_rq,
  1815. struct sched_domain *sd, enum idle_type idle)
  1816. {
  1817. struct sched_group *group;
  1818. runqueue_t *busiest;
  1819. unsigned long imbalance;
  1820. int nr_moved, all_pinned = 0;
  1821. int active_balance = 0;
  1822. int sd_idle = 0;
  1823. if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER)
  1824. sd_idle = 1;
  1825. schedstat_inc(sd, lb_cnt[idle]);
  1826. group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
  1827. if (!group) {
  1828. schedstat_inc(sd, lb_nobusyg[idle]);
  1829. goto out_balanced;
  1830. }
  1831. busiest = find_busiest_queue(group);
  1832. if (!busiest) {
  1833. schedstat_inc(sd, lb_nobusyq[idle]);
  1834. goto out_balanced;
  1835. }
  1836. BUG_ON(busiest == this_rq);
  1837. schedstat_add(sd, lb_imbalance[idle], imbalance);
  1838. nr_moved = 0;
  1839. if (busiest->nr_running > 1) {
  1840. /*
  1841. * Attempt to move tasks. If find_busiest_group has found
  1842. * an imbalance but busiest->nr_running <= 1, the group is
  1843. * still unbalanced. nr_moved simply stays zero, so it is
  1844. * correctly treated as an imbalance.
  1845. */
  1846. double_rq_lock(this_rq, busiest);
  1847. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  1848. imbalance, sd, idle, &all_pinned);
  1849. double_rq_unlock(this_rq, busiest);
  1850. /* All tasks on this runqueue were pinned by CPU affinity */
  1851. if (unlikely(all_pinned))
  1852. goto out_balanced;
  1853. }
  1854. if (!nr_moved) {
  1855. schedstat_inc(sd, lb_failed[idle]);
  1856. sd->nr_balance_failed++;
  1857. if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
  1858. spin_lock(&busiest->lock);
  1859. /* don't kick the migration_thread, if the curr
  1860. * task on busiest cpu can't be moved to this_cpu
  1861. */
  1862. if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
  1863. spin_unlock(&busiest->lock);
  1864. all_pinned = 1;
  1865. goto out_one_pinned;
  1866. }
  1867. if (!busiest->active_balance) {
  1868. busiest->active_balance = 1;
  1869. busiest->push_cpu = this_cpu;
  1870. active_balance = 1;
  1871. }
  1872. spin_unlock(&busiest->lock);
  1873. if (active_balance)
  1874. wake_up_process(busiest->migration_thread);
  1875. /*
  1876. * We've kicked active balancing, reset the failure
  1877. * counter.
  1878. */
  1879. sd->nr_balance_failed = sd->cache_nice_tries+1;
  1880. }
  1881. } else
  1882. sd->nr_balance_failed = 0;
  1883. if (likely(!active_balance)) {
  1884. /* We were unbalanced, so reset the balancing interval */
  1885. sd->balance_interval = sd->min_interval;
  1886. } else {
  1887. /*
  1888. * If we've begun active balancing, start to back off. This
  1889. * case may not be covered by the all_pinned logic if there
  1890. * is only 1 task on the busy runqueue (because we don't call
  1891. * move_tasks).
  1892. */
  1893. if (sd->balance_interval < sd->max_interval)
  1894. sd->balance_interval *= 2;
  1895. }
  1896. if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1897. return -1;
  1898. return nr_moved;
  1899. out_balanced:
  1900. schedstat_inc(sd, lb_balanced[idle]);
  1901. sd->nr_balance_failed = 0;
  1902. out_one_pinned:
  1903. /* tune up the balancing interval */
  1904. if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
  1905. (sd->balance_interval < sd->max_interval))
  1906. sd->balance_interval *= 2;
  1907. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1908. return -1;
  1909. return 0;
  1910. }
  1911. /*
  1912. * Check this_cpu to ensure it is balanced within domain. Attempt to move
  1913. * tasks if there is an imbalance.
  1914. *
  1915. * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
  1916. * this_rq is locked.
  1917. */
  1918. static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
  1919. struct sched_domain *sd)
  1920. {
  1921. struct sched_group *group;
  1922. runqueue_t *busiest = NULL;
  1923. unsigned long imbalance;
  1924. int nr_moved = 0;
  1925. int sd_idle = 0;
  1926. if (sd->flags & SD_SHARE_CPUPOWER)
  1927. sd_idle = 1;
  1928. schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
  1929. group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
  1930. if (!group) {
  1931. schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
  1932. goto out_balanced;
  1933. }
  1934. busiest = find_busiest_queue(group);
  1935. if (!busiest) {
  1936. schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
  1937. goto out_balanced;
  1938. }
  1939. BUG_ON(busiest == this_rq);
  1940. schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
  1941. nr_moved = 0;
  1942. if (busiest->nr_running > 1) {
  1943. /* Attempt to move tasks */
  1944. double_lock_balance(this_rq, busiest);
  1945. nr_moved = move_tasks(this_rq, this_cpu, busiest,
  1946. imbalance, sd, NEWLY_IDLE, NULL);
  1947. spin_unlock(&busiest->lock);
  1948. }
  1949. if (!nr_moved) {
  1950. schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
  1951. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1952. return -1;
  1953. } else
  1954. sd->nr_balance_failed = 0;
  1955. return nr_moved;
  1956. out_balanced:
  1957. schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
  1958. if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
  1959. return -1;
  1960. sd->nr_balance_failed = 0;
  1961. return 0;
  1962. }
  1963. /*
  1964. * idle_balance is called by schedule() if this_cpu is about to become
  1965. * idle. Attempts to pull tasks from other CPUs.
  1966. */
  1967. static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
  1968. {
  1969. struct sched_domain *sd;
  1970. for_each_domain(this_cpu, sd) {
  1971. if (sd->flags & SD_BALANCE_NEWIDLE) {
  1972. if (load_balance_newidle(this_cpu, this_rq, sd)) {
  1973. /* We've pulled tasks over so stop searching */
  1974. break;
  1975. }
  1976. }
  1977. }
  1978. }
  1979. /*
  1980. * active_load_balance is run by migration threads. It pushes running tasks
  1981. * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
  1982. * running on each physical CPU where possible, and avoids physical /
  1983. * logical imbalances.
  1984. *
  1985. * Called with busiest_rq locked.
  1986. */
  1987. static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
  1988. {
  1989. struct sched_domain *sd;
  1990. runqueue_t *target_rq;
  1991. int target_cpu = busiest_rq->push_cpu;
  1992. if (busiest_rq->nr_running <= 1)
  1993. /* no task to move */
  1994. return;
  1995. target_rq = cpu_rq(target_cpu);
  1996. /*
  1997. * This condition is "impossible", if it occurs
  1998. * we need to fix it. Originally reported by
  1999. * Bjorn Helgaas on a 128-cpu setup.
  2000. */
  2001. BUG_ON(busiest_rq == target_rq);
  2002. /* move a task from busiest_rq to target_rq */
  2003. double_lock_balance(busiest_rq, target_rq);
  2004. /* Search for an sd spanning us and the target CPU. */
  2005. for_each_domain(target_cpu, sd)
  2006. if ((sd->flags & SD_LOAD_BALANCE) &&
  2007. cpu_isset(busiest_cpu, sd->span))
  2008. break;
  2009. if (unlikely(sd == NULL))
  2010. goto out;
  2011. schedstat_inc(sd, alb_cnt);
  2012. if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
  2013. schedstat_inc(sd, alb_pushed);
  2014. else
  2015. schedstat_inc(sd, alb_failed);
  2016. out:
  2017. spin_unlock(&target_rq->lock);
  2018. }
  2019. /*
  2020. * rebalance_tick will get called every timer tick, on every CPU.
  2021. *
  2022. * It checks each scheduling domain to see if it is due to be balanced,
  2023. * and initiates a balancing operation if so.
  2024. *
  2025. * Balancing parameters are set up in arch_init_sched_domains.
  2026. */
  2027. /* Don't have all balancing operations going off at once */
  2028. #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
  2029. static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
  2030. enum idle_type idle)
  2031. {
  2032. unsigned long old_load, this_load;
  2033. unsigned long j = jiffies + CPU_OFFSET(this_cpu);
  2034. struct sched_domain *sd;
  2035. int i;
  2036. this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
  2037. /* Update our load */
  2038. for (i = 0; i < 3; i++) {
  2039. unsigned long new_load = this_load;
  2040. int scale = 1 << i;
  2041. old_load = this_rq->cpu_load[i];
  2042. /*
  2043. * Round up the averaging division if load is increasing. This
  2044. * prevents us from getting stuck on 9 if the load is 10, for
  2045. * example.
  2046. */
  2047. if (new_load > old_load)
  2048. new_load += scale-1;
  2049. this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
  2050. }
  2051. for_each_domain(this_cpu, sd) {
  2052. unsigned long interval;
  2053. if (!(sd->flags & SD_LOAD_BALANCE))
  2054. continue;
  2055. interval = sd->balance_interval;
  2056. if (idle != SCHED_IDLE)
  2057. interval *= sd->busy_factor;
  2058. /* scale ms to jiffies */
  2059. interval = msecs_to_jiffies(interval);
  2060. if (unlikely(!interval))
  2061. interval = 1;
  2062. if (j - sd->last_balance >= interval) {
  2063. if (load_balance(this_cpu, this_rq, sd, idle)) {
  2064. /*
  2065. * We've pulled tasks over so either we're no
  2066. * longer idle, or one of our SMT siblings is
  2067. * not idle.
  2068. */
  2069. idle = NOT_IDLE;
  2070. }
  2071. sd->last_balance += interval;
  2072. }
  2073. }
  2074. }
  2075. #else
  2076. /*
  2077. * on UP we do not need to balance between CPUs:
  2078. */
  2079. static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
  2080. {
  2081. }
  2082. static inline void idle_balance(int cpu, runqueue_t *rq)
  2083. {
  2084. }
  2085. #endif
  2086. static inline int wake_priority_sleeper(runqueue_t *rq)
  2087. {
  2088. int ret = 0;
  2089. #ifdef CONFIG_SCHED_SMT
  2090. spin_lock(&rq->lock);
  2091. /*
  2092. * If an SMT sibling task has been put to sleep for priority
  2093. * reasons reschedule the idle task to see if it can now run.
  2094. */
  2095. if (rq->nr_running) {
  2096. resched_task(rq->idle);
  2097. ret = 1;
  2098. }
  2099. spin_unlock(&rq->lock);
  2100. #endif
  2101. return ret;
  2102. }
  2103. DEFINE_PER_CPU(struct kernel_stat, kstat);
  2104. EXPORT_PER_CPU_SYMBOL(kstat);
  2105. /*
  2106. * This is called on clock ticks and on context switches.
  2107. * Bank in p->sched_time the ns elapsed since the last tick or switch.
  2108. */
  2109. static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
  2110. unsigned long long now)
  2111. {
  2112. unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
  2113. p->sched_time += now - last;
  2114. }
  2115. /*
  2116. * Return current->sched_time plus any more ns on the sched_clock
  2117. * that have not yet been banked.
  2118. */
  2119. unsigned long long current_sched_time(const task_t *tsk)
  2120. {
  2121. unsigned long long ns;
  2122. unsigned long flags;
  2123. local_irq_save(flags);
  2124. ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
  2125. ns = tsk->sched_time + (sched_clock() - ns);
  2126. local_irq_restore(flags);
  2127. return ns;
  2128. }
  2129. /*
  2130. * We place interactive tasks back into the active array, if possible.
  2131. *
  2132. * To guarantee that this does not starve expired tasks we ignore the
  2133. * interactivity of a task if the first expired task had to wait more
  2134. * than a 'reasonable' amount of time. This deadline timeout is
  2135. * load-dependent, as the frequency of array switched decreases with
  2136. * increasing number of running tasks. We also ignore the interactivity
  2137. * if a better static_prio task has expired:
  2138. */
  2139. #define EXPIRED_STARVING(rq) \
  2140. ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
  2141. (jiffies - (rq)->expired_timestamp >= \
  2142. STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
  2143. ((rq)->curr->static_prio > (rq)->best_expired_prio))
  2144. /*
  2145. * Account user cpu time to a process.
  2146. * @p: the process that the cpu time gets accounted to
  2147. * @hardirq_offset: the offset to subtract from hardirq_count()
  2148. * @cputime: the cpu time spent in user space since the last update
  2149. */
  2150. void account_user_time(struct task_struct *p, cputime_t cputime)
  2151. {
  2152. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2153. cputime64_t tmp;
  2154. p->utime = cputime_add(p->utime, cputime);
  2155. /* Add user time to cpustat. */
  2156. tmp = cputime_to_cputime64(cputime);
  2157. if (TASK_NICE(p) > 0)
  2158. cpustat->nice = cputime64_add(cpustat->nice, tmp);
  2159. else
  2160. cpustat->user = cputime64_add(cpustat->user, tmp);
  2161. }
  2162. /*
  2163. * Account system cpu time to a process.
  2164. * @p: the process that the cpu time gets accounted to
  2165. * @hardirq_offset: the offset to subtract from hardirq_count()
  2166. * @cputime: the cpu time spent in kernel space since the last update
  2167. */
  2168. void account_system_time(struct task_struct *p, int hardirq_offset,
  2169. cputime_t cputime)
  2170. {
  2171. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2172. runqueue_t *rq = this_rq();
  2173. cputime64_t tmp;
  2174. p->stime = cputime_add(p->stime, cputime);
  2175. /* Add system time to cpustat. */
  2176. tmp = cputime_to_cputime64(cputime);
  2177. if (hardirq_count() - hardirq_offset)
  2178. cpustat->irq = cputime64_add(cpustat->irq, tmp);
  2179. else if (softirq_count())
  2180. cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
  2181. else if (p != rq->idle)
  2182. cpustat->system = cputime64_add(cpustat->system, tmp);
  2183. else if (atomic_read(&rq->nr_iowait) > 0)
  2184. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2185. else
  2186. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2187. /* Account for system time used */
  2188. acct_update_integrals(p);
  2189. /* Update rss highwater mark */
  2190. update_mem_hiwater(p);
  2191. }
  2192. /*
  2193. * Account for involuntary wait time.
  2194. * @p: the process from which the cpu time has been stolen
  2195. * @steal: the cpu time spent in involuntary wait
  2196. */
  2197. void account_steal_time(struct task_struct *p, cputime_t steal)
  2198. {
  2199. struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
  2200. cputime64_t tmp = cputime_to_cputime64(steal);
  2201. runqueue_t *rq = this_rq();
  2202. if (p == rq->idle) {
  2203. p->stime = cputime_add(p->stime, steal);
  2204. if (atomic_read(&rq->nr_iowait) > 0)
  2205. cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
  2206. else
  2207. cpustat->idle = cputime64_add(cpustat->idle, tmp);
  2208. } else
  2209. cpustat->steal = cputime64_add(cpustat->steal, tmp);
  2210. }
  2211. /*
  2212. * This function gets called by the timer code, with HZ frequency.
  2213. * We call it with interrupts disabled.
  2214. *
  2215. * It also gets called by the fork code, when changing the parent's
  2216. * timeslices.
  2217. */
  2218. void scheduler_tick(void)
  2219. {
  2220. int cpu = smp_processor_id();
  2221. runqueue_t *rq = this_rq();
  2222. task_t *p = current;
  2223. unsigned long long now = sched_clock();
  2224. update_cpu_clock(p, rq, now);
  2225. rq->timestamp_last_tick = now;
  2226. if (p == rq->idle) {
  2227. if (wake_priority_sleeper(rq))
  2228. goto out;
  2229. rebalance_tick(cpu, rq, SCHED_IDLE);
  2230. return;
  2231. }
  2232. /* Task might have expired already, but not scheduled off yet */
  2233. if (p->array != rq->active) {
  2234. set_tsk_need_resched(p);
  2235. goto out;
  2236. }
  2237. spin_lock(&rq->lock);
  2238. /*
  2239. * The task was running during this tick - update the
  2240. * time slice counter. Note: we do not update a thread's
  2241. * priority until it either goes to sleep or uses up its
  2242. * timeslice. This makes it possible for interactive tasks
  2243. * to use up their timeslices at their highest priority levels.
  2244. */
  2245. if (rt_task(p)) {
  2246. /*
  2247. * RR tasks need a special form of timeslice management.
  2248. * FIFO tasks have no timeslices.
  2249. */
  2250. if ((p->policy == SCHED_RR) && !--p->time_slice) {
  2251. p->time_slice = task_timeslice(p);
  2252. p->first_time_slice = 0;
  2253. set_tsk_need_resched(p);
  2254. /* put it at the end of the queue: */
  2255. requeue_task(p, rq->active);
  2256. }
  2257. goto out_unlock;
  2258. }
  2259. if (!--p->time_slice) {
  2260. dequeue_task(p, rq->active);
  2261. set_tsk_need_resched(p);
  2262. p->prio = effective_prio(p);
  2263. p->time_slice = task_timeslice(p);
  2264. p->first_time_slice = 0;
  2265. if (!rq->expired_timestamp)
  2266. rq->expired_timestamp = jiffies;
  2267. if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
  2268. enqueue_task(p, rq->expired);
  2269. if (p->static_prio < rq->best_expired_prio)
  2270. rq->best_expired_prio = p->static_prio;
  2271. } else
  2272. enqueue_task(p, rq->active);
  2273. } else {
  2274. /*
  2275. * Prevent a too long timeslice allowing a task to monopolize
  2276. * the CPU. We do this by splitting up the timeslice into
  2277. * smaller pieces.
  2278. *
  2279. * Note: this does not mean the task's timeslices expire or
  2280. * get lost in any way, they just might be preempted by
  2281. * another task of equal priority. (one with higher
  2282. * priority would have preempted this task already.) We
  2283. * requeue this task to the end of the list on this priority
  2284. * level, which is in essence a round-robin of tasks with
  2285. * equal priority.
  2286. *
  2287. * This only applies to tasks in the interactive
  2288. * delta range with at least TIMESLICE_GRANULARITY to requeue.
  2289. */
  2290. if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
  2291. p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
  2292. (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
  2293. (p->array == rq->active)) {
  2294. requeue_task(p, rq->active);
  2295. set_tsk_need_resched(p);
  2296. }
  2297. }
  2298. out_unlock:
  2299. spin_unlock(&rq->lock);
  2300. out:
  2301. rebalance_tick(cpu, rq, NOT_IDLE);
  2302. }
  2303. #ifdef CONFIG_SCHED_SMT
  2304. static inline void wakeup_busy_runqueue(runqueue_t *rq)
  2305. {
  2306. /* If an SMT runqueue is sleeping due to priority reasons wake it up */
  2307. if (rq->curr == rq->idle && rq->nr_running)
  2308. resched_task(rq->idle);
  2309. }
  2310. static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
  2311. {
  2312. struct sched_domain *tmp, *sd = NULL;
  2313. cpumask_t sibling_map;
  2314. int i;
  2315. for_each_domain(this_cpu, tmp)
  2316. if (tmp->flags & SD_SHARE_CPUPOWER)
  2317. sd = tmp;
  2318. if (!sd)
  2319. return;
  2320. /*
  2321. * Unlock the current runqueue because we have to lock in
  2322. * CPU order to avoid deadlocks. Caller knows that we might
  2323. * unlock. We keep IRQs disabled.
  2324. */
  2325. spin_unlock(&this_rq->lock);
  2326. sibling_map = sd->span;
  2327. for_each_cpu_mask(i, sibling_map)
  2328. spin_lock(&cpu_rq(i)->lock);
  2329. /*
  2330. * We clear this CPU from the mask. This both simplifies the
  2331. * inner loop and keps this_rq locked when we exit:
  2332. */
  2333. cpu_clear(this_cpu, sibling_map);
  2334. for_each_cpu_mask(i, sibling_map) {
  2335. runqueue_t *smt_rq = cpu_rq(i);
  2336. wakeup_busy_runqueue(smt_rq);
  2337. }
  2338. for_each_cpu_mask(i, sibling_map)
  2339. spin_unlock(&cpu_rq(i)->lock);
  2340. /*
  2341. * We exit with this_cpu's rq still held and IRQs
  2342. * still disabled:
  2343. */
  2344. }
  2345. /*
  2346. * number of 'lost' timeslices this task wont be able to fully
  2347. * utilize, if another task runs on a sibling. This models the
  2348. * slowdown effect of other tasks running on siblings:
  2349. */
  2350. static inline unsigned long smt_slice(task_t *p, struct sched_domain *sd)
  2351. {
  2352. return p->time_slice * (100 - sd->per_cpu_gain) / 100;
  2353. }
  2354. static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
  2355. {
  2356. struct sched_domain *tmp, *sd = NULL;
  2357. cpumask_t sibling_map;
  2358. prio_array_t *array;
  2359. int ret = 0, i;
  2360. task_t *p;
  2361. for_each_domain(this_cpu, tmp)
  2362. if (tmp->flags & SD_SHARE_CPUPOWER)
  2363. sd = tmp;
  2364. if (!sd)
  2365. return 0;
  2366. /*
  2367. * The same locking rules and details apply as for
  2368. * wake_sleeping_dependent():
  2369. */
  2370. spin_unlock(&this_rq->lock);
  2371. sibling_map = sd->span;
  2372. for_each_cpu_mask(i, sibling_map)
  2373. spin_lock(&cpu_rq(i)->lock);
  2374. cpu_clear(this_cpu, sibling_map);
  2375. /*
  2376. * Establish next task to be run - it might have gone away because
  2377. * we released the runqueue lock above:
  2378. */
  2379. if (!this_rq->nr_running)
  2380. goto out_unlock;
  2381. array = this_rq->active;
  2382. if (!array->nr_active)
  2383. array = this_rq->expired;
  2384. BUG_ON(!array->nr_active);
  2385. p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
  2386. task_t, run_list);
  2387. for_each_cpu_mask(i, sibling_map) {
  2388. runqueue_t *smt_rq = cpu_rq(i);
  2389. task_t *smt_curr = smt_rq->curr;
  2390. /* Kernel threads do not participate in dependent sleeping */
  2391. if (!p->mm || !smt_curr->mm || rt_task(p))
  2392. goto check_smt_task;
  2393. /*
  2394. * If a user task with lower static priority than the
  2395. * running task on the SMT sibling is trying to schedule,
  2396. * delay it till there is proportionately less timeslice
  2397. * left of the sibling task to prevent a lower priority
  2398. * task from using an unfair proportion of the
  2399. * physical cpu's resources. -ck
  2400. */
  2401. if (rt_task(smt_curr)) {
  2402. /*
  2403. * With real time tasks we run non-rt tasks only
  2404. * per_cpu_gain% of the time.
  2405. */
  2406. if ((jiffies % DEF_TIMESLICE) >
  2407. (sd->per_cpu_gain * DEF_TIMESLICE / 100))
  2408. ret = 1;
  2409. } else
  2410. if (smt_curr->static_prio < p->static_prio &&
  2411. !TASK_PREEMPTS_CURR(p, smt_rq) &&
  2412. smt_slice(smt_curr, sd) > task_timeslice(p))
  2413. ret = 1;
  2414. check_smt_task:
  2415. if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
  2416. rt_task(smt_curr))
  2417. continue;
  2418. if (!p->mm) {
  2419. wakeup_busy_runqueue(smt_rq);
  2420. continue;
  2421. }
  2422. /*
  2423. * Reschedule a lower priority task on the SMT sibling for
  2424. * it to be put to sleep, or wake it up if it has been put to
  2425. * sleep for priority reasons to see if it should run now.
  2426. */
  2427. if (rt_task(p)) {
  2428. if ((jiffies % DEF_TIMESLICE) >
  2429. (sd->per_cpu_gain * DEF_TIMESLICE / 100))
  2430. resched_task(smt_curr);
  2431. } else {
  2432. if (TASK_PREEMPTS_CURR(p, smt_rq) &&
  2433. smt_slice(p, sd) > task_timeslice(smt_curr))
  2434. resched_task(smt_curr);
  2435. else
  2436. wakeup_busy_runqueue(smt_rq);
  2437. }
  2438. }
  2439. out_unlock:
  2440. for_each_cpu_mask(i, sibling_map)
  2441. spin_unlock(&cpu_rq(i)->lock);
  2442. return ret;
  2443. }
  2444. #else
  2445. static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
  2446. {
  2447. }
  2448. static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
  2449. {
  2450. return 0;
  2451. }
  2452. #endif
  2453. #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
  2454. void fastcall add_preempt_count(int val)
  2455. {
  2456. /*
  2457. * Underflow?
  2458. */
  2459. BUG_ON((preempt_count() < 0));
  2460. preempt_count() += val;
  2461. /*
  2462. * Spinlock count overflowing soon?
  2463. */
  2464. BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
  2465. }
  2466. EXPORT_SYMBOL(add_preempt_count);
  2467. void fastcall sub_preempt_count(int val)
  2468. {
  2469. /*
  2470. * Underflow?
  2471. */
  2472. BUG_ON(val > preempt_count());
  2473. /*
  2474. * Is the spinlock portion underflowing?
  2475. */
  2476. BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
  2477. preempt_count() -= val;
  2478. }
  2479. EXPORT_SYMBOL(sub_preempt_count);
  2480. #endif
  2481. /*
  2482. * schedule() is the main scheduler function.
  2483. */
  2484. asmlinkage void __sched schedule(void)
  2485. {
  2486. long *switch_count;
  2487. task_t *prev, *next;
  2488. runqueue_t *rq;
  2489. prio_array_t *array;
  2490. struct list_head *queue;
  2491. unsigned long long now;
  2492. unsigned long run_time;
  2493. int cpu, idx, new_prio;
  2494. /*
  2495. * Test if we are atomic. Since do_exit() needs to call into
  2496. * schedule() atomically, we ignore that path for now.
  2497. * Otherwise, whine if we are scheduling when we should not be.
  2498. */
  2499. if (likely(!current->exit_state)) {
  2500. if (unlikely(in_atomic())) {
  2501. printk(KERN_ERR "scheduling while atomic: "
  2502. "%s/0x%08x/%d\n",
  2503. current->comm, preempt_count(), current->pid);
  2504. dump_stack();
  2505. }
  2506. }
  2507. profile_hit(SCHED_PROFILING, __builtin_return_address(0));
  2508. need_resched:
  2509. preempt_disable();
  2510. prev = current;
  2511. release_kernel_lock(prev);
  2512. need_resched_nonpreemptible:
  2513. rq = this_rq();
  2514. /*
  2515. * The idle thread is not allowed to schedule!
  2516. * Remove this check after it has been exercised a bit.
  2517. */
  2518. if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
  2519. printk(KERN_ERR "bad: scheduling from the idle thread!\n");
  2520. dump_stack();
  2521. }
  2522. schedstat_inc(rq, sched_cnt);
  2523. now = sched_clock();
  2524. if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
  2525. run_time = now - prev->timestamp;
  2526. if (unlikely((long long)(now - prev->timestamp) < 0))
  2527. run_time = 0;
  2528. } else
  2529. run_time = NS_MAX_SLEEP_AVG;
  2530. /*
  2531. * Tasks charged proportionately less run_time at high sleep_avg to
  2532. * delay them losing their interactive status
  2533. */
  2534. run_time /= (CURRENT_BONUS(prev) ? : 1);
  2535. spin_lock_irq(&rq->lock);
  2536. if (unlikely(prev->flags & PF_DEAD))
  2537. prev->state = EXIT_DEAD;
  2538. switch_count = &prev->nivcsw;
  2539. if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
  2540. switch_count = &prev->nvcsw;
  2541. if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
  2542. unlikely(signal_pending(prev))))
  2543. prev->state = TASK_RUNNING;
  2544. else {
  2545. if (prev->state == TASK_UNINTERRUPTIBLE)
  2546. rq->nr_uninterruptible++;
  2547. deactivate_task(prev, rq);
  2548. }
  2549. }
  2550. cpu = smp_processor_id();
  2551. if (unlikely(!rq->nr_running)) {
  2552. go_idle:
  2553. idle_balance(cpu, rq);
  2554. if (!rq->nr_running) {
  2555. next = rq->idle;
  2556. rq->expired_timestamp = 0;
  2557. wake_sleeping_dependent(cpu, rq);
  2558. /*
  2559. * wake_sleeping_dependent() might have released
  2560. * the runqueue, so break out if we got new
  2561. * tasks meanwhile:
  2562. */
  2563. if (!rq->nr_running)
  2564. goto switch_tasks;
  2565. }
  2566. } else {
  2567. if (dependent_sleeper(cpu, rq)) {
  2568. next = rq->idle;
  2569. goto switch_tasks;
  2570. }
  2571. /*
  2572. * dependent_sleeper() releases and reacquires the runqueue
  2573. * lock, hence go into the idle loop if the rq went
  2574. * empty meanwhile:
  2575. */
  2576. if (unlikely(!rq->nr_running))
  2577. goto go_idle;
  2578. }
  2579. array = rq->active;
  2580. if (unlikely(!array->nr_active)) {
  2581. /*
  2582. * Switch the active and expired arrays.
  2583. */
  2584. schedstat_inc(rq, sched_switch);
  2585. rq->active = rq->expired;
  2586. rq->expired = array;
  2587. array = rq->active;
  2588. rq->expired_timestamp = 0;
  2589. rq->best_expired_prio = MAX_PRIO;
  2590. }
  2591. idx = sched_find_first_bit(array->bitmap);
  2592. queue = array->queue + idx;
  2593. next = list_entry(queue->next, task_t, run_list);
  2594. if (!rt_task(next) && next->activated > 0) {
  2595. unsigned long long delta = now - next->timestamp;
  2596. if (unlikely((long long)(now - next->timestamp) < 0))
  2597. delta = 0;
  2598. if (next->activated == 1)
  2599. delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
  2600. array = next->array;
  2601. new_prio = recalc_task_prio(next, next->timestamp + delta);
  2602. if (unlikely(next->prio != new_prio)) {
  2603. dequeue_task(next, array);
  2604. next->prio = new_prio;
  2605. enqueue_task(next, array);
  2606. } else
  2607. requeue_task(next, array);
  2608. }
  2609. next->activated = 0;
  2610. switch_tasks:
  2611. if (next == rq->idle)
  2612. schedstat_inc(rq, sched_goidle);
  2613. prefetch(next);
  2614. prefetch_stack(next);
  2615. clear_tsk_need_resched(prev);
  2616. rcu_qsctr_inc(task_cpu(prev));
  2617. update_cpu_clock(prev, rq, now);
  2618. prev->sleep_avg -= run_time;
  2619. if ((long)prev->sleep_avg <= 0)
  2620. prev->sleep_avg = 0;
  2621. prev->timestamp = prev->last_ran = now;
  2622. sched_info_switch(prev, next);
  2623. if (likely(prev != next)) {
  2624. next->timestamp = now;
  2625. rq->nr_switches++;
  2626. rq->curr = next;
  2627. ++*switch_count;
  2628. prepare_task_switch(rq, next);
  2629. prev = context_switch(rq, prev, next);
  2630. barrier();
  2631. /*
  2632. * this_rq must be evaluated again because prev may have moved
  2633. * CPUs since it called schedule(), thus the 'rq' on its stack
  2634. * frame will be invalid.
  2635. */
  2636. finish_task_switch(this_rq(), prev);
  2637. } else
  2638. spin_unlock_irq(&rq->lock);
  2639. prev = current;
  2640. if (unlikely(reacquire_kernel_lock(prev) < 0))
  2641. goto need_resched_nonpreemptible;
  2642. preempt_enable_no_resched();
  2643. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2644. goto need_resched;
  2645. }
  2646. EXPORT_SYMBOL(schedule);
  2647. #ifdef CONFIG_PREEMPT
  2648. /*
  2649. * this is is the entry point to schedule() from in-kernel preemption
  2650. * off of preempt_enable. Kernel preemptions off return from interrupt
  2651. * occur there and call schedule directly.
  2652. */
  2653. asmlinkage void __sched preempt_schedule(void)
  2654. {
  2655. struct thread_info *ti = current_thread_info();
  2656. #ifdef CONFIG_PREEMPT_BKL
  2657. struct task_struct *task = current;
  2658. int saved_lock_depth;
  2659. #endif
  2660. /*
  2661. * If there is a non-zero preempt_count or interrupts are disabled,
  2662. * we do not want to preempt the current task. Just return..
  2663. */
  2664. if (unlikely(ti->preempt_count || irqs_disabled()))
  2665. return;
  2666. need_resched:
  2667. add_preempt_count(PREEMPT_ACTIVE);
  2668. /*
  2669. * We keep the big kernel semaphore locked, but we
  2670. * clear ->lock_depth so that schedule() doesnt
  2671. * auto-release the semaphore:
  2672. */
  2673. #ifdef CONFIG_PREEMPT_BKL
  2674. saved_lock_depth = task->lock_depth;
  2675. task->lock_depth = -1;
  2676. #endif
  2677. schedule();
  2678. #ifdef CONFIG_PREEMPT_BKL
  2679. task->lock_depth = saved_lock_depth;
  2680. #endif
  2681. sub_preempt_count(PREEMPT_ACTIVE);
  2682. /* we could miss a preemption opportunity between schedule and now */
  2683. barrier();
  2684. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2685. goto need_resched;
  2686. }
  2687. EXPORT_SYMBOL(preempt_schedule);
  2688. /*
  2689. * this is is the entry point to schedule() from kernel preemption
  2690. * off of irq context.
  2691. * Note, that this is called and return with irqs disabled. This will
  2692. * protect us against recursive calling from irq.
  2693. */
  2694. asmlinkage void __sched preempt_schedule_irq(void)
  2695. {
  2696. struct thread_info *ti = current_thread_info();
  2697. #ifdef CONFIG_PREEMPT_BKL
  2698. struct task_struct *task = current;
  2699. int saved_lock_depth;
  2700. #endif
  2701. /* Catch callers which need to be fixed*/
  2702. BUG_ON(ti->preempt_count || !irqs_disabled());
  2703. need_resched:
  2704. add_preempt_count(PREEMPT_ACTIVE);
  2705. /*
  2706. * We keep the big kernel semaphore locked, but we
  2707. * clear ->lock_depth so that schedule() doesnt
  2708. * auto-release the semaphore:
  2709. */
  2710. #ifdef CONFIG_PREEMPT_BKL
  2711. saved_lock_depth = task->lock_depth;
  2712. task->lock_depth = -1;
  2713. #endif
  2714. local_irq_enable();
  2715. schedule();
  2716. local_irq_disable();
  2717. #ifdef CONFIG_PREEMPT_BKL
  2718. task->lock_depth = saved_lock_depth;
  2719. #endif
  2720. sub_preempt_count(PREEMPT_ACTIVE);
  2721. /* we could miss a preemption opportunity between schedule and now */
  2722. barrier();
  2723. if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
  2724. goto need_resched;
  2725. }
  2726. #endif /* CONFIG_PREEMPT */
  2727. int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
  2728. void *key)
  2729. {
  2730. task_t *p = curr->private;
  2731. return try_to_wake_up(p, mode, sync);
  2732. }
  2733. EXPORT_SYMBOL(default_wake_function);
  2734. /*
  2735. * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
  2736. * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
  2737. * number) then we wake all the non-exclusive tasks and one exclusive task.
  2738. *
  2739. * There are circumstances in which we can try to wake a task which has already
  2740. * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
  2741. * zero in this (rare) case, and we handle it by continuing to scan the queue.
  2742. */
  2743. static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
  2744. int nr_exclusive, int sync, void *key)
  2745. {
  2746. struct list_head *tmp, *next;
  2747. list_for_each_safe(tmp, next, &q->task_list) {
  2748. wait_queue_t *curr;
  2749. unsigned flags;
  2750. curr = list_entry(tmp, wait_queue_t, task_list);
  2751. flags = curr->flags;
  2752. if (curr->func(curr, mode, sync, key) &&
  2753. (flags & WQ_FLAG_EXCLUSIVE) &&
  2754. !--nr_exclusive)
  2755. break;
  2756. }
  2757. }
  2758. /**
  2759. * __wake_up - wake up threads blocked on a waitqueue.
  2760. * @q: the waitqueue
  2761. * @mode: which threads
  2762. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  2763. * @key: is directly passed to the wakeup function
  2764. */
  2765. void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
  2766. int nr_exclusive, void *key)
  2767. {
  2768. unsigned long flags;
  2769. spin_lock_irqsave(&q->lock, flags);
  2770. __wake_up_common(q, mode, nr_exclusive, 0, key);
  2771. spin_unlock_irqrestore(&q->lock, flags);
  2772. }
  2773. EXPORT_SYMBOL(__wake_up);
  2774. /*
  2775. * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
  2776. */
  2777. void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
  2778. {
  2779. __wake_up_common(q, mode, 1, 0, NULL);
  2780. }
  2781. /**
  2782. * __wake_up_sync - wake up threads blocked on a waitqueue.
  2783. * @q: the waitqueue
  2784. * @mode: which threads
  2785. * @nr_exclusive: how many wake-one or wake-many threads to wake up
  2786. *
  2787. * The sync wakeup differs that the waker knows that it will schedule
  2788. * away soon, so while the target thread will be woken up, it will not
  2789. * be migrated to another CPU - ie. the two threads are 'synchronized'
  2790. * with each other. This can prevent needless bouncing between CPUs.
  2791. *
  2792. * On UP it can prevent extra preemption.
  2793. */
  2794. void fastcall
  2795. __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
  2796. {
  2797. unsigned long flags;
  2798. int sync = 1;
  2799. if (unlikely(!q))
  2800. return;
  2801. if (unlikely(!nr_exclusive))
  2802. sync = 0;
  2803. spin_lock_irqsave(&q->lock, flags);
  2804. __wake_up_common(q, mode, nr_exclusive, sync, NULL);
  2805. spin_unlock_irqrestore(&q->lock, flags);
  2806. }
  2807. EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
  2808. void fastcall complete(struct completion *x)
  2809. {
  2810. unsigned long flags;
  2811. spin_lock_irqsave(&x->wait.lock, flags);
  2812. x->done++;
  2813. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  2814. 1, 0, NULL);
  2815. spin_unlock_irqrestore(&x->wait.lock, flags);
  2816. }
  2817. EXPORT_SYMBOL(complete);
  2818. void fastcall complete_all(struct completion *x)
  2819. {
  2820. unsigned long flags;
  2821. spin_lock_irqsave(&x->wait.lock, flags);
  2822. x->done += UINT_MAX/2;
  2823. __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
  2824. 0, 0, NULL);
  2825. spin_unlock_irqrestore(&x->wait.lock, flags);
  2826. }
  2827. EXPORT_SYMBOL(complete_all);
  2828. void fastcall __sched wait_for_completion(struct completion *x)
  2829. {
  2830. might_sleep();
  2831. spin_lock_irq(&x->wait.lock);
  2832. if (!x->done) {
  2833. DECLARE_WAITQUEUE(wait, current);
  2834. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2835. __add_wait_queue_tail(&x->wait, &wait);
  2836. do {
  2837. __set_current_state(TASK_UNINTERRUPTIBLE);
  2838. spin_unlock_irq(&x->wait.lock);
  2839. schedule();
  2840. spin_lock_irq(&x->wait.lock);
  2841. } while (!x->done);
  2842. __remove_wait_queue(&x->wait, &wait);
  2843. }
  2844. x->done--;
  2845. spin_unlock_irq(&x->wait.lock);
  2846. }
  2847. EXPORT_SYMBOL(wait_for_completion);
  2848. unsigned long fastcall __sched
  2849. wait_for_completion_timeout(struct completion *x, unsigned long timeout)
  2850. {
  2851. might_sleep();
  2852. spin_lock_irq(&x->wait.lock);
  2853. if (!x->done) {
  2854. DECLARE_WAITQUEUE(wait, current);
  2855. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2856. __add_wait_queue_tail(&x->wait, &wait);
  2857. do {
  2858. __set_current_state(TASK_UNINTERRUPTIBLE);
  2859. spin_unlock_irq(&x->wait.lock);
  2860. timeout = schedule_timeout(timeout);
  2861. spin_lock_irq(&x->wait.lock);
  2862. if (!timeout) {
  2863. __remove_wait_queue(&x->wait, &wait);
  2864. goto out;
  2865. }
  2866. } while (!x->done);
  2867. __remove_wait_queue(&x->wait, &wait);
  2868. }
  2869. x->done--;
  2870. out:
  2871. spin_unlock_irq(&x->wait.lock);
  2872. return timeout;
  2873. }
  2874. EXPORT_SYMBOL(wait_for_completion_timeout);
  2875. int fastcall __sched wait_for_completion_interruptible(struct completion *x)
  2876. {
  2877. int ret = 0;
  2878. might_sleep();
  2879. spin_lock_irq(&x->wait.lock);
  2880. if (!x->done) {
  2881. DECLARE_WAITQUEUE(wait, current);
  2882. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2883. __add_wait_queue_tail(&x->wait, &wait);
  2884. do {
  2885. if (signal_pending(current)) {
  2886. ret = -ERESTARTSYS;
  2887. __remove_wait_queue(&x->wait, &wait);
  2888. goto out;
  2889. }
  2890. __set_current_state(TASK_INTERRUPTIBLE);
  2891. spin_unlock_irq(&x->wait.lock);
  2892. schedule();
  2893. spin_lock_irq(&x->wait.lock);
  2894. } while (!x->done);
  2895. __remove_wait_queue(&x->wait, &wait);
  2896. }
  2897. x->done--;
  2898. out:
  2899. spin_unlock_irq(&x->wait.lock);
  2900. return ret;
  2901. }
  2902. EXPORT_SYMBOL(wait_for_completion_interruptible);
  2903. unsigned long fastcall __sched
  2904. wait_for_completion_interruptible_timeout(struct completion *x,
  2905. unsigned long timeout)
  2906. {
  2907. might_sleep();
  2908. spin_lock_irq(&x->wait.lock);
  2909. if (!x->done) {
  2910. DECLARE_WAITQUEUE(wait, current);
  2911. wait.flags |= WQ_FLAG_EXCLUSIVE;
  2912. __add_wait_queue_tail(&x->wait, &wait);
  2913. do {
  2914. if (signal_pending(current)) {
  2915. timeout = -ERESTARTSYS;
  2916. __remove_wait_queue(&x->wait, &wait);
  2917. goto out;
  2918. }
  2919. __set_current_state(TASK_INTERRUPTIBLE);
  2920. spin_unlock_irq(&x->wait.lock);
  2921. timeout = schedule_timeout(timeout);
  2922. spin_lock_irq(&x->wait.lock);
  2923. if (!timeout) {
  2924. __remove_wait_queue(&x->wait, &wait);
  2925. goto out;
  2926. }
  2927. } while (!x->done);
  2928. __remove_wait_queue(&x->wait, &wait);
  2929. }
  2930. x->done--;
  2931. out:
  2932. spin_unlock_irq(&x->wait.lock);
  2933. return timeout;
  2934. }
  2935. EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
  2936. #define SLEEP_ON_VAR \
  2937. unsigned long flags; \
  2938. wait_queue_t wait; \
  2939. init_waitqueue_entry(&wait, current);
  2940. #define SLEEP_ON_HEAD \
  2941. spin_lock_irqsave(&q->lock,flags); \
  2942. __add_wait_queue(q, &wait); \
  2943. spin_unlock(&q->lock);
  2944. #define SLEEP_ON_TAIL \
  2945. spin_lock_irq(&q->lock); \
  2946. __remove_wait_queue(q, &wait); \
  2947. spin_unlock_irqrestore(&q->lock, flags);
  2948. void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
  2949. {
  2950. SLEEP_ON_VAR
  2951. current->state = TASK_INTERRUPTIBLE;
  2952. SLEEP_ON_HEAD
  2953. schedule();
  2954. SLEEP_ON_TAIL
  2955. }
  2956. EXPORT_SYMBOL(interruptible_sleep_on);
  2957. long fastcall __sched
  2958. interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
  2959. {
  2960. SLEEP_ON_VAR
  2961. current->state = TASK_INTERRUPTIBLE;
  2962. SLEEP_ON_HEAD
  2963. timeout = schedule_timeout(timeout);
  2964. SLEEP_ON_TAIL
  2965. return timeout;
  2966. }
  2967. EXPORT_SYMBOL(interruptible_sleep_on_timeout);
  2968. void fastcall __sched sleep_on(wait_queue_head_t *q)
  2969. {
  2970. SLEEP_ON_VAR
  2971. current->state = TASK_UNINTERRUPTIBLE;
  2972. SLEEP_ON_HEAD
  2973. schedule();
  2974. SLEEP_ON_TAIL
  2975. }
  2976. EXPORT_SYMBOL(sleep_on);
  2977. long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
  2978. {
  2979. SLEEP_ON_VAR
  2980. current->state = TASK_UNINTERRUPTIBLE;
  2981. SLEEP_ON_HEAD
  2982. timeout = schedule_timeout(timeout);
  2983. SLEEP_ON_TAIL
  2984. return timeout;
  2985. }
  2986. EXPORT_SYMBOL(sleep_on_timeout);
  2987. void set_user_nice(task_t *p, long nice)
  2988. {
  2989. unsigned long flags;
  2990. prio_array_t *array;
  2991. runqueue_t *rq;
  2992. int old_prio, new_prio, delta;
  2993. if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
  2994. return;
  2995. /*
  2996. * We have to be careful, if called from sys_setpriority(),
  2997. * the task might be in the middle of scheduling on another CPU.
  2998. */
  2999. rq = task_rq_lock(p, &flags);
  3000. /*
  3001. * The RT priorities are set via sched_setscheduler(), but we still
  3002. * allow the 'normal' nice value to be set - but as expected
  3003. * it wont have any effect on scheduling until the task is
  3004. * not SCHED_NORMAL:
  3005. */
  3006. if (rt_task(p)) {
  3007. p->static_prio = NICE_TO_PRIO(nice);
  3008. goto out_unlock;
  3009. }
  3010. array = p->array;
  3011. if (array)
  3012. dequeue_task(p, array);
  3013. old_prio = p->prio;
  3014. new_prio = NICE_TO_PRIO(nice);
  3015. delta = new_prio - old_prio;
  3016. p->static_prio = NICE_TO_PRIO(nice);
  3017. p->prio += delta;
  3018. if (array) {
  3019. enqueue_task(p, array);
  3020. /*
  3021. * If the task increased its priority or is running and
  3022. * lowered its priority, then reschedule its CPU:
  3023. */
  3024. if (delta < 0 || (delta > 0 && task_running(rq, p)))
  3025. resched_task(rq->curr);
  3026. }
  3027. out_unlock:
  3028. task_rq_unlock(rq, &flags);
  3029. }
  3030. EXPORT_SYMBOL(set_user_nice);
  3031. /*
  3032. * can_nice - check if a task can reduce its nice value
  3033. * @p: task
  3034. * @nice: nice value
  3035. */
  3036. int can_nice(const task_t *p, const int nice)
  3037. {
  3038. /* convert nice value [19,-20] to rlimit style value [1,40] */
  3039. int nice_rlim = 20 - nice;
  3040. return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
  3041. capable(CAP_SYS_NICE));
  3042. }
  3043. #ifdef __ARCH_WANT_SYS_NICE
  3044. /*
  3045. * sys_nice - change the priority of the current process.
  3046. * @increment: priority increment
  3047. *
  3048. * sys_setpriority is a more generic, but much slower function that
  3049. * does similar things.
  3050. */
  3051. asmlinkage long sys_nice(int increment)
  3052. {
  3053. int retval;
  3054. long nice;
  3055. /*
  3056. * Setpriority might change our priority at the same moment.
  3057. * We don't have to worry. Conceptually one call occurs first
  3058. * and we have a single winner.
  3059. */
  3060. if (increment < -40)
  3061. increment = -40;
  3062. if (increment > 40)
  3063. increment = 40;
  3064. nice = PRIO_TO_NICE(current->static_prio) + increment;
  3065. if (nice < -20)
  3066. nice = -20;
  3067. if (nice > 19)
  3068. nice = 19;
  3069. if (increment < 0 && !can_nice(current, nice))
  3070. return -EPERM;
  3071. retval = security_task_setnice(current, nice);
  3072. if (retval)
  3073. return retval;
  3074. set_user_nice(current, nice);
  3075. return 0;
  3076. }
  3077. #endif
  3078. /**
  3079. * task_prio - return the priority value of a given task.
  3080. * @p: the task in question.
  3081. *
  3082. * This is the priority value as seen by users in /proc.
  3083. * RT tasks are offset by -200. Normal tasks are centered
  3084. * around 0, value goes from -16 to +15.
  3085. */
  3086. int task_prio(const task_t *p)
  3087. {
  3088. return p->prio - MAX_RT_PRIO;
  3089. }
  3090. /**
  3091. * task_nice - return the nice value of a given task.
  3092. * @p: the task in question.
  3093. */
  3094. int task_nice(const task_t *p)
  3095. {
  3096. return TASK_NICE(p);
  3097. }
  3098. EXPORT_SYMBOL_GPL(task_nice);
  3099. /**
  3100. * idle_cpu - is a given cpu idle currently?
  3101. * @cpu: the processor in question.
  3102. */
  3103. int idle_cpu(int cpu)
  3104. {
  3105. return cpu_curr(cpu) == cpu_rq(cpu)->idle;
  3106. }
  3107. EXPORT_SYMBOL_GPL(idle_cpu);
  3108. /**
  3109. * idle_task - return the idle task for a given cpu.
  3110. * @cpu: the processor in question.
  3111. */
  3112. task_t *idle_task(int cpu)
  3113. {
  3114. return cpu_rq(cpu)->idle;
  3115. }
  3116. /**
  3117. * find_process_by_pid - find a process with a matching PID value.
  3118. * @pid: the pid in question.
  3119. */
  3120. static inline task_t *find_process_by_pid(pid_t pid)
  3121. {
  3122. return pid ? find_task_by_pid(pid) : current;
  3123. }
  3124. /* Actually do priority change: must hold rq lock. */
  3125. static void __setscheduler(struct task_struct *p, int policy, int prio)
  3126. {
  3127. BUG_ON(p->array);
  3128. p->policy = policy;
  3129. p->rt_priority = prio;
  3130. if (policy != SCHED_NORMAL)
  3131. p->prio = MAX_RT_PRIO-1 - p->rt_priority;
  3132. else
  3133. p->prio = p->static_prio;
  3134. }
  3135. /**
  3136. * sched_setscheduler - change the scheduling policy and/or RT priority of
  3137. * a thread.
  3138. * @p: the task in question.
  3139. * @policy: new policy.
  3140. * @param: structure containing the new RT priority.
  3141. */
  3142. int sched_setscheduler(struct task_struct *p, int policy,
  3143. struct sched_param *param)
  3144. {
  3145. int retval;
  3146. int oldprio, oldpolicy = -1;
  3147. prio_array_t *array;
  3148. unsigned long flags;
  3149. runqueue_t *rq;
  3150. recheck:
  3151. /* double check policy once rq lock held */
  3152. if (policy < 0)
  3153. policy = oldpolicy = p->policy;
  3154. else if (policy != SCHED_FIFO && policy != SCHED_RR &&
  3155. policy != SCHED_NORMAL)
  3156. return -EINVAL;
  3157. /*
  3158. * Valid priorities for SCHED_FIFO and SCHED_RR are
  3159. * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
  3160. */
  3161. if (param->sched_priority < 0 ||
  3162. (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
  3163. (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
  3164. return -EINVAL;
  3165. if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
  3166. return -EINVAL;
  3167. /*
  3168. * Allow unprivileged RT tasks to decrease priority:
  3169. */
  3170. if (!capable(CAP_SYS_NICE)) {
  3171. /* can't change policy */
  3172. if (policy != p->policy &&
  3173. !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
  3174. return -EPERM;
  3175. /* can't increase priority */
  3176. if (policy != SCHED_NORMAL &&
  3177. param->sched_priority > p->rt_priority &&
  3178. param->sched_priority >
  3179. p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
  3180. return -EPERM;
  3181. /* can't change other user's priorities */
  3182. if ((current->euid != p->euid) &&
  3183. (current->euid != p->uid))
  3184. return -EPERM;
  3185. }
  3186. retval = security_task_setscheduler(p, policy, param);
  3187. if (retval)
  3188. return retval;
  3189. /*
  3190. * To be able to change p->policy safely, the apropriate
  3191. * runqueue lock must be held.
  3192. */
  3193. rq = task_rq_lock(p, &flags);
  3194. /* recheck policy now with rq lock held */
  3195. if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
  3196. policy = oldpolicy = -1;
  3197. task_rq_unlock(rq, &flags);
  3198. goto recheck;
  3199. }
  3200. array = p->array;
  3201. if (array)
  3202. deactivate_task(p, rq);
  3203. oldprio = p->prio;
  3204. __setscheduler(p, policy, param->sched_priority);
  3205. if (array) {
  3206. __activate_task(p, rq);
  3207. /*
  3208. * Reschedule if we are currently running on this runqueue and
  3209. * our priority decreased, or if we are not currently running on
  3210. * this runqueue and our priority is higher than the current's
  3211. */
  3212. if (task_running(rq, p)) {
  3213. if (p->prio > oldprio)
  3214. resched_task(rq->curr);
  3215. } else if (TASK_PREEMPTS_CURR(p, rq))
  3216. resched_task(rq->curr);
  3217. }
  3218. task_rq_unlock(rq, &flags);
  3219. return 0;
  3220. }
  3221. EXPORT_SYMBOL_GPL(sched_setscheduler);
  3222. static int
  3223. do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
  3224. {
  3225. int retval;
  3226. struct sched_param lparam;
  3227. struct task_struct *p;
  3228. if (!param || pid < 0)
  3229. return -EINVAL;
  3230. if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
  3231. return -EFAULT;
  3232. read_lock_irq(&tasklist_lock);
  3233. p = find_process_by_pid(pid);
  3234. if (!p) {
  3235. read_unlock_irq(&tasklist_lock);
  3236. return -ESRCH;
  3237. }
  3238. retval = sched_setscheduler(p, policy, &lparam);
  3239. read_unlock_irq(&tasklist_lock);
  3240. return retval;
  3241. }
  3242. /**
  3243. * sys_sched_setscheduler - set/change the scheduler policy and RT priority
  3244. * @pid: the pid in question.
  3245. * @policy: new policy.
  3246. * @param: structure containing the new RT priority.
  3247. */
  3248. asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
  3249. struct sched_param __user *param)
  3250. {
  3251. return do_sched_setscheduler(pid, policy, param);
  3252. }
  3253. /**
  3254. * sys_sched_setparam - set/change the RT priority of a thread
  3255. * @pid: the pid in question.
  3256. * @param: structure containing the new RT priority.
  3257. */
  3258. asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
  3259. {
  3260. return do_sched_setscheduler(pid, -1, param);
  3261. }
  3262. /**
  3263. * sys_sched_getscheduler - get the policy (scheduling class) of a thread
  3264. * @pid: the pid in question.
  3265. */
  3266. asmlinkage long sys_sched_getscheduler(pid_t pid)
  3267. {
  3268. int retval = -EINVAL;
  3269. task_t *p;
  3270. if (pid < 0)
  3271. goto out_nounlock;
  3272. retval = -ESRCH;
  3273. read_lock(&tasklist_lock);
  3274. p = find_process_by_pid(pid);
  3275. if (p) {
  3276. retval = security_task_getscheduler(p);
  3277. if (!retval)
  3278. retval = p->policy;
  3279. }
  3280. read_unlock(&tasklist_lock);
  3281. out_nounlock:
  3282. return retval;
  3283. }
  3284. /**
  3285. * sys_sched_getscheduler - get the RT priority of a thread
  3286. * @pid: the pid in question.
  3287. * @param: structure containing the RT priority.
  3288. */
  3289. asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
  3290. {
  3291. struct sched_param lp;
  3292. int retval = -EINVAL;
  3293. task_t *p;
  3294. if (!param || pid < 0)
  3295. goto out_nounlock;
  3296. read_lock(&tasklist_lock);
  3297. p = find_process_by_pid(pid);
  3298. retval = -ESRCH;
  3299. if (!p)
  3300. goto out_unlock;
  3301. retval = security_task_getscheduler(p);
  3302. if (retval)
  3303. goto out_unlock;
  3304. lp.sched_priority = p->rt_priority;
  3305. read_unlock(&tasklist_lock);
  3306. /*
  3307. * This one might sleep, we cannot do it with a spinlock held ...
  3308. */
  3309. retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
  3310. out_nounlock:
  3311. return retval;
  3312. out_unlock:
  3313. read_unlock(&tasklist_lock);
  3314. return retval;
  3315. }
  3316. long sched_setaffinity(pid_t pid, cpumask_t new_mask)
  3317. {
  3318. task_t *p;
  3319. int retval;
  3320. cpumask_t cpus_allowed;
  3321. lock_cpu_hotplug();
  3322. read_lock(&tasklist_lock);
  3323. p = find_process_by_pid(pid);
  3324. if (!p) {
  3325. read_unlock(&tasklist_lock);
  3326. unlock_cpu_hotplug();
  3327. return -ESRCH;
  3328. }
  3329. /*
  3330. * It is not safe to call set_cpus_allowed with the
  3331. * tasklist_lock held. We will bump the task_struct's
  3332. * usage count and then drop tasklist_lock.
  3333. */
  3334. get_task_struct(p);
  3335. read_unlock(&tasklist_lock);
  3336. retval = -EPERM;
  3337. if ((current->euid != p->euid) && (current->euid != p->uid) &&
  3338. !capable(CAP_SYS_NICE))
  3339. goto out_unlock;
  3340. cpus_allowed = cpuset_cpus_allowed(p);
  3341. cpus_and(new_mask, new_mask, cpus_allowed);
  3342. retval = set_cpus_allowed(p, new_mask);
  3343. out_unlock:
  3344. put_task_struct(p);
  3345. unlock_cpu_hotplug();
  3346. return retval;
  3347. }
  3348. static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
  3349. cpumask_t *new_mask)
  3350. {
  3351. if (len < sizeof(cpumask_t)) {
  3352. memset(new_mask, 0, sizeof(cpumask_t));
  3353. } else if (len > sizeof(cpumask_t)) {
  3354. len = sizeof(cpumask_t);
  3355. }
  3356. return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
  3357. }
  3358. /**
  3359. * sys_sched_setaffinity - set the cpu affinity of a process
  3360. * @pid: pid of the process
  3361. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3362. * @user_mask_ptr: user-space pointer to the new cpu mask
  3363. */
  3364. asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
  3365. unsigned long __user *user_mask_ptr)
  3366. {
  3367. cpumask_t new_mask;
  3368. int retval;
  3369. retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
  3370. if (retval)
  3371. return retval;
  3372. return sched_setaffinity(pid, new_mask);
  3373. }
  3374. /*
  3375. * Represents all cpu's present in the system
  3376. * In systems capable of hotplug, this map could dynamically grow
  3377. * as new cpu's are detected in the system via any platform specific
  3378. * method, such as ACPI for e.g.
  3379. */
  3380. cpumask_t cpu_present_map;
  3381. EXPORT_SYMBOL(cpu_present_map);
  3382. #ifndef CONFIG_SMP
  3383. cpumask_t cpu_online_map = CPU_MASK_ALL;
  3384. cpumask_t cpu_possible_map = CPU_MASK_ALL;
  3385. #endif
  3386. long sched_getaffinity(pid_t pid, cpumask_t *mask)
  3387. {
  3388. int retval;
  3389. task_t *p;
  3390. lock_cpu_hotplug();
  3391. read_lock(&tasklist_lock);
  3392. retval = -ESRCH;
  3393. p = find_process_by_pid(pid);
  3394. if (!p)
  3395. goto out_unlock;
  3396. retval = 0;
  3397. cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
  3398. out_unlock:
  3399. read_unlock(&tasklist_lock);
  3400. unlock_cpu_hotplug();
  3401. if (retval)
  3402. return retval;
  3403. return 0;
  3404. }
  3405. /**
  3406. * sys_sched_getaffinity - get the cpu affinity of a process
  3407. * @pid: pid of the process
  3408. * @len: length in bytes of the bitmask pointed to by user_mask_ptr
  3409. * @user_mask_ptr: user-space pointer to hold the current cpu mask
  3410. */
  3411. asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
  3412. unsigned long __user *user_mask_ptr)
  3413. {
  3414. int ret;
  3415. cpumask_t mask;
  3416. if (len < sizeof(cpumask_t))
  3417. return -EINVAL;
  3418. ret = sched_getaffinity(pid, &mask);
  3419. if (ret < 0)
  3420. return ret;
  3421. if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
  3422. return -EFAULT;
  3423. return sizeof(cpumask_t);
  3424. }
  3425. /**
  3426. * sys_sched_yield - yield the current processor to other threads.
  3427. *
  3428. * this function yields the current CPU by moving the calling thread
  3429. * to the expired array. If there are no other threads running on this
  3430. * CPU then this function will return.
  3431. */
  3432. asmlinkage long sys_sched_yield(void)
  3433. {
  3434. runqueue_t *rq = this_rq_lock();
  3435. prio_array_t *array = current->array;
  3436. prio_array_t *target = rq->expired;
  3437. schedstat_inc(rq, yld_cnt);
  3438. /*
  3439. * We implement yielding by moving the task into the expired
  3440. * queue.
  3441. *
  3442. * (special rule: RT tasks will just roundrobin in the active
  3443. * array.)
  3444. */
  3445. if (rt_task(current))
  3446. target = rq->active;
  3447. if (array->nr_active == 1) {
  3448. schedstat_inc(rq, yld_act_empty);
  3449. if (!rq->expired->nr_active)
  3450. schedstat_inc(rq, yld_both_empty);
  3451. } else if (!rq->expired->nr_active)
  3452. schedstat_inc(rq, yld_exp_empty);
  3453. if (array != target) {
  3454. dequeue_task(current, array);
  3455. enqueue_task(current, target);
  3456. } else
  3457. /*
  3458. * requeue_task is cheaper so perform that if possible.
  3459. */
  3460. requeue_task(current, array);
  3461. /*
  3462. * Since we are going to call schedule() anyway, there's
  3463. * no need to preempt or enable interrupts:
  3464. */
  3465. __release(rq->lock);
  3466. _raw_spin_unlock(&rq->lock);
  3467. preempt_enable_no_resched();
  3468. schedule();
  3469. return 0;
  3470. }
  3471. static inline void __cond_resched(void)
  3472. {
  3473. /*
  3474. * The BKS might be reacquired before we have dropped
  3475. * PREEMPT_ACTIVE, which could trigger a second
  3476. * cond_resched() call.
  3477. */
  3478. if (unlikely(preempt_count()))
  3479. return;
  3480. do {
  3481. add_preempt_count(PREEMPT_ACTIVE);
  3482. schedule();
  3483. sub_preempt_count(PREEMPT_ACTIVE);
  3484. } while (need_resched());
  3485. }
  3486. int __sched cond_resched(void)
  3487. {
  3488. if (need_resched()) {
  3489. __cond_resched();
  3490. return 1;
  3491. }
  3492. return 0;
  3493. }
  3494. EXPORT_SYMBOL(cond_resched);
  3495. /*
  3496. * cond_resched_lock() - if a reschedule is pending, drop the given lock,
  3497. * call schedule, and on return reacquire the lock.
  3498. *
  3499. * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
  3500. * operations here to prevent schedule() from being called twice (once via
  3501. * spin_unlock(), once by hand).
  3502. */
  3503. int cond_resched_lock(spinlock_t *lock)
  3504. {
  3505. int ret = 0;
  3506. if (need_lockbreak(lock)) {
  3507. spin_unlock(lock);
  3508. cpu_relax();
  3509. ret = 1;
  3510. spin_lock(lock);
  3511. }
  3512. if (need_resched()) {
  3513. _raw_spin_unlock(lock);
  3514. preempt_enable_no_resched();
  3515. __cond_resched();
  3516. ret = 1;
  3517. spin_lock(lock);
  3518. }
  3519. return ret;
  3520. }
  3521. EXPORT_SYMBOL(cond_resched_lock);
  3522. int __sched cond_resched_softirq(void)
  3523. {
  3524. BUG_ON(!in_softirq());
  3525. if (need_resched()) {
  3526. __local_bh_enable();
  3527. __cond_resched();
  3528. local_bh_disable();
  3529. return 1;
  3530. }
  3531. return 0;
  3532. }
  3533. EXPORT_SYMBOL(cond_resched_softirq);
  3534. /**
  3535. * yield - yield the current processor to other threads.
  3536. *
  3537. * this is a shortcut for kernel-space yielding - it marks the
  3538. * thread runnable and calls sys_sched_yield().
  3539. */
  3540. void __sched yield(void)
  3541. {
  3542. set_current_state(TASK_RUNNING);
  3543. sys_sched_yield();
  3544. }
  3545. EXPORT_SYMBOL(yield);
  3546. /*
  3547. * This task is about to go to sleep on IO. Increment rq->nr_iowait so
  3548. * that process accounting knows that this is a task in IO wait state.
  3549. *
  3550. * But don't do that if it is a deliberate, throttling IO wait (this task
  3551. * has set its backing_dev_info: the queue against which it should throttle)
  3552. */
  3553. void __sched io_schedule(void)
  3554. {
  3555. struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
  3556. atomic_inc(&rq->nr_iowait);
  3557. schedule();
  3558. atomic_dec(&rq->nr_iowait);
  3559. }
  3560. EXPORT_SYMBOL(io_schedule);
  3561. long __sched io_schedule_timeout(long timeout)
  3562. {
  3563. struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
  3564. long ret;
  3565. atomic_inc(&rq->nr_iowait);
  3566. ret = schedule_timeout(timeout);
  3567. atomic_dec(&rq->nr_iowait);
  3568. return ret;
  3569. }
  3570. /**
  3571. * sys_sched_get_priority_max - return maximum RT priority.
  3572. * @policy: scheduling class.
  3573. *
  3574. * this syscall returns the maximum rt_priority that can be used
  3575. * by a given scheduling class.
  3576. */
  3577. asmlinkage long sys_sched_get_priority_max(int policy)
  3578. {
  3579. int ret = -EINVAL;
  3580. switch (policy) {
  3581. case SCHED_FIFO:
  3582. case SCHED_RR:
  3583. ret = MAX_USER_RT_PRIO-1;
  3584. break;
  3585. case SCHED_NORMAL:
  3586. ret = 0;
  3587. break;
  3588. }
  3589. return ret;
  3590. }
  3591. /**
  3592. * sys_sched_get_priority_min - return minimum RT priority.
  3593. * @policy: scheduling class.
  3594. *
  3595. * this syscall returns the minimum rt_priority that can be used
  3596. * by a given scheduling class.
  3597. */
  3598. asmlinkage long sys_sched_get_priority_min(int policy)
  3599. {
  3600. int ret = -EINVAL;
  3601. switch (policy) {
  3602. case SCHED_FIFO:
  3603. case SCHED_RR:
  3604. ret = 1;
  3605. break;
  3606. case SCHED_NORMAL:
  3607. ret = 0;
  3608. }
  3609. return ret;
  3610. }
  3611. /**
  3612. * sys_sched_rr_get_interval - return the default timeslice of a process.
  3613. * @pid: pid of the process.
  3614. * @interval: userspace pointer to the timeslice value.
  3615. *
  3616. * this syscall writes the default timeslice value of a given process
  3617. * into the user-space timespec buffer. A value of '0' means infinity.
  3618. */
  3619. asmlinkage
  3620. long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
  3621. {
  3622. int retval = -EINVAL;
  3623. struct timespec t;
  3624. task_t *p;
  3625. if (pid < 0)
  3626. goto out_nounlock;
  3627. retval = -ESRCH;
  3628. read_lock(&tasklist_lock);
  3629. p = find_process_by_pid(pid);
  3630. if (!p)
  3631. goto out_unlock;
  3632. retval = security_task_getscheduler(p);
  3633. if (retval)
  3634. goto out_unlock;
  3635. jiffies_to_timespec(p->policy & SCHED_FIFO ?
  3636. 0 : task_timeslice(p), &t);
  3637. read_unlock(&tasklist_lock);
  3638. retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
  3639. out_nounlock:
  3640. return retval;
  3641. out_unlock:
  3642. read_unlock(&tasklist_lock);
  3643. return retval;
  3644. }
  3645. static inline struct task_struct *eldest_child(struct task_struct *p)
  3646. {
  3647. if (list_empty(&p->children)) return NULL;
  3648. return list_entry(p->children.next,struct task_struct,sibling);
  3649. }
  3650. static inline struct task_struct *older_sibling(struct task_struct *p)
  3651. {
  3652. if (p->sibling.prev==&p->parent->children) return NULL;
  3653. return list_entry(p->sibling.prev,struct task_struct,sibling);
  3654. }
  3655. static inline struct task_struct *younger_sibling(struct task_struct *p)
  3656. {
  3657. if (p->sibling.next==&p->parent->children) return NULL;
  3658. return list_entry(p->sibling.next,struct task_struct,sibling);
  3659. }
  3660. static void show_task(task_t *p)
  3661. {
  3662. task_t *relative;
  3663. unsigned state;
  3664. unsigned long free = 0;
  3665. static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
  3666. printk("%-13.13s ", p->comm);
  3667. state = p->state ? __ffs(p->state) + 1 : 0;
  3668. if (state < ARRAY_SIZE(stat_nam))
  3669. printk(stat_nam[state]);
  3670. else
  3671. printk("?");
  3672. #if (BITS_PER_LONG == 32)
  3673. if (state == TASK_RUNNING)
  3674. printk(" running ");
  3675. else
  3676. printk(" %08lX ", thread_saved_pc(p));
  3677. #else
  3678. if (state == TASK_RUNNING)
  3679. printk(" running task ");
  3680. else
  3681. printk(" %016lx ", thread_saved_pc(p));
  3682. #endif
  3683. #ifdef CONFIG_DEBUG_STACK_USAGE
  3684. {
  3685. unsigned long *n = (unsigned long *) (p->thread_info+1);
  3686. while (!*n)
  3687. n++;
  3688. free = (unsigned long) n - (unsigned long)(p->thread_info+1);
  3689. }
  3690. #endif
  3691. printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
  3692. if ((relative = eldest_child(p)))
  3693. printk("%5d ", relative->pid);
  3694. else
  3695. printk(" ");
  3696. if ((relative = younger_sibling(p)))
  3697. printk("%7d", relative->pid);
  3698. else
  3699. printk(" ");
  3700. if ((relative = older_sibling(p)))
  3701. printk(" %5d", relative->pid);
  3702. else
  3703. printk(" ");
  3704. if (!p->mm)
  3705. printk(" (L-TLB)\n");
  3706. else
  3707. printk(" (NOTLB)\n");
  3708. if (state != TASK_RUNNING)
  3709. show_stack(p, NULL);
  3710. }
  3711. void show_state(void)
  3712. {
  3713. task_t *g, *p;
  3714. #if (BITS_PER_LONG == 32)
  3715. printk("\n"
  3716. " sibling\n");
  3717. printk(" task PC pid father child younger older\n");
  3718. #else
  3719. printk("\n"
  3720. " sibling\n");
  3721. printk(" task PC pid father child younger older\n");
  3722. #endif
  3723. read_lock(&tasklist_lock);
  3724. do_each_thread(g, p) {
  3725. /*
  3726. * reset the NMI-timeout, listing all files on a slow
  3727. * console might take alot of time:
  3728. */
  3729. touch_nmi_watchdog();
  3730. show_task(p);
  3731. } while_each_thread(g, p);
  3732. read_unlock(&tasklist_lock);
  3733. }
  3734. /**
  3735. * init_idle - set up an idle thread for a given CPU
  3736. * @idle: task in question
  3737. * @cpu: cpu the idle task belongs to
  3738. *
  3739. * NOTE: this function does not set the idle thread's NEED_RESCHED
  3740. * flag, to make booting more robust.
  3741. */
  3742. void __devinit init_idle(task_t *idle, int cpu)
  3743. {
  3744. runqueue_t *rq = cpu_rq(cpu);
  3745. unsigned long flags;
  3746. idle->sleep_avg = 0;
  3747. idle->array = NULL;
  3748. idle->prio = MAX_PRIO;
  3749. idle->state = TASK_RUNNING;
  3750. idle->cpus_allowed = cpumask_of_cpu(cpu);
  3751. set_task_cpu(idle, cpu);
  3752. spin_lock_irqsave(&rq->lock, flags);
  3753. rq->curr = rq->idle = idle;
  3754. #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
  3755. idle->oncpu = 1;
  3756. #endif
  3757. spin_unlock_irqrestore(&rq->lock, flags);
  3758. /* Set the preempt count _outside_ the spinlocks! */
  3759. #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
  3760. idle->thread_info->preempt_count = (idle->lock_depth >= 0);
  3761. #else
  3762. idle->thread_info->preempt_count = 0;
  3763. #endif
  3764. }
  3765. /*
  3766. * In a system that switches off the HZ timer nohz_cpu_mask
  3767. * indicates which cpus entered this state. This is used
  3768. * in the rcu update to wait only for active cpus. For system
  3769. * which do not switch off the HZ timer nohz_cpu_mask should
  3770. * always be CPU_MASK_NONE.
  3771. */
  3772. cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
  3773. #ifdef CONFIG_SMP
  3774. /*
  3775. * This is how migration works:
  3776. *
  3777. * 1) we queue a migration_req_t structure in the source CPU's
  3778. * runqueue and wake up that CPU's migration thread.
  3779. * 2) we down() the locked semaphore => thread blocks.
  3780. * 3) migration thread wakes up (implicitly it forces the migrated
  3781. * thread off the CPU)
  3782. * 4) it gets the migration request and checks whether the migrated
  3783. * task is still in the wrong runqueue.
  3784. * 5) if it's in the wrong runqueue then the migration thread removes
  3785. * it and puts it into the right queue.
  3786. * 6) migration thread up()s the semaphore.
  3787. * 7) we wake up and the migration is done.
  3788. */
  3789. /*
  3790. * Change a given task's CPU affinity. Migrate the thread to a
  3791. * proper CPU and schedule it away if the CPU it's executing on
  3792. * is removed from the allowed bitmask.
  3793. *
  3794. * NOTE: the caller must have a valid reference to the task, the
  3795. * task must not exit() & deallocate itself prematurely. The
  3796. * call is not atomic; no spinlocks may be held.
  3797. */
  3798. int set_cpus_allowed(task_t *p, cpumask_t new_mask)
  3799. {
  3800. unsigned long flags;
  3801. int ret = 0;
  3802. migration_req_t req;
  3803. runqueue_t *rq;
  3804. rq = task_rq_lock(p, &flags);
  3805. if (!cpus_intersects(new_mask, cpu_online_map)) {
  3806. ret = -EINVAL;
  3807. goto out;
  3808. }
  3809. p->cpus_allowed = new_mask;
  3810. /* Can the task run on the task's current CPU? If so, we're done */
  3811. if (cpu_isset(task_cpu(p), new_mask))
  3812. goto out;
  3813. if (migrate_task(p, any_online_cpu(new_mask), &req)) {
  3814. /* Need help from migration thread: drop lock and wait. */
  3815. task_rq_unlock(rq, &flags);
  3816. wake_up_process(rq->migration_thread);
  3817. wait_for_completion(&req.done);
  3818. tlb_migrate_finish(p->mm);
  3819. return 0;
  3820. }
  3821. out:
  3822. task_rq_unlock(rq, &flags);
  3823. return ret;
  3824. }
  3825. EXPORT_SYMBOL_GPL(set_cpus_allowed);
  3826. /*
  3827. * Move (not current) task off this cpu, onto dest cpu. We're doing
  3828. * this because either it can't run here any more (set_cpus_allowed()
  3829. * away from this CPU, or CPU going down), or because we're
  3830. * attempting to rebalance this task on exec (sched_exec).
  3831. *
  3832. * So we race with normal scheduler movements, but that's OK, as long
  3833. * as the task is no longer on this CPU.
  3834. */
  3835. static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
  3836. {
  3837. runqueue_t *rq_dest, *rq_src;
  3838. if (unlikely(cpu_is_offline(dest_cpu)))
  3839. return;
  3840. rq_src = cpu_rq(src_cpu);
  3841. rq_dest = cpu_rq(dest_cpu);
  3842. double_rq_lock(rq_src, rq_dest);
  3843. /* Already moved. */
  3844. if (task_cpu(p) != src_cpu)
  3845. goto out;
  3846. /* Affinity changed (again). */
  3847. if (!cpu_isset(dest_cpu, p->cpus_allowed))
  3848. goto out;
  3849. set_task_cpu(p, dest_cpu);
  3850. if (p->array) {
  3851. /*
  3852. * Sync timestamp with rq_dest's before activating.
  3853. * The same thing could be achieved by doing this step
  3854. * afterwards, and pretending it was a local activate.
  3855. * This way is cleaner and logically correct.
  3856. */
  3857. p->timestamp = p->timestamp - rq_src->timestamp_last_tick
  3858. + rq_dest->timestamp_last_tick;
  3859. deactivate_task(p, rq_src);
  3860. activate_task(p, rq_dest, 0);
  3861. if (TASK_PREEMPTS_CURR(p, rq_dest))
  3862. resched_task(rq_dest->curr);
  3863. }
  3864. out:
  3865. double_rq_unlock(rq_src, rq_dest);
  3866. }
  3867. /*
  3868. * migration_thread - this is a highprio system thread that performs
  3869. * thread migration by bumping thread off CPU then 'pushing' onto
  3870. * another runqueue.
  3871. */
  3872. static int migration_thread(void *data)
  3873. {
  3874. runqueue_t *rq;
  3875. int cpu = (long)data;
  3876. rq = cpu_rq(cpu);
  3877. BUG_ON(rq->migration_thread != current);
  3878. set_current_state(TASK_INTERRUPTIBLE);
  3879. while (!kthread_should_stop()) {
  3880. struct list_head *head;
  3881. migration_req_t *req;
  3882. try_to_freeze();
  3883. spin_lock_irq(&rq->lock);
  3884. if (cpu_is_offline(cpu)) {
  3885. spin_unlock_irq(&rq->lock);
  3886. goto wait_to_die;
  3887. }
  3888. if (rq->active_balance) {
  3889. active_load_balance(rq, cpu);
  3890. rq->active_balance = 0;
  3891. }
  3892. head = &rq->migration_queue;
  3893. if (list_empty(head)) {
  3894. spin_unlock_irq(&rq->lock);
  3895. schedule();
  3896. set_current_state(TASK_INTERRUPTIBLE);
  3897. continue;
  3898. }
  3899. req = list_entry(head->next, migration_req_t, list);
  3900. list_del_init(head->next);
  3901. spin_unlock(&rq->lock);
  3902. __migrate_task(req->task, cpu, req->dest_cpu);
  3903. local_irq_enable();
  3904. complete(&req->done);
  3905. }
  3906. __set_current_state(TASK_RUNNING);
  3907. return 0;
  3908. wait_to_die:
  3909. /* Wait for kthread_stop */
  3910. set_current_state(TASK_INTERRUPTIBLE);
  3911. while (!kthread_should_stop()) {
  3912. schedule();
  3913. set_current_state(TASK_INTERRUPTIBLE);
  3914. }
  3915. __set_current_state(TASK_RUNNING);
  3916. return 0;
  3917. }
  3918. #ifdef CONFIG_HOTPLUG_CPU
  3919. /* Figure out where task on dead CPU should go, use force if neccessary. */
  3920. static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
  3921. {
  3922. int dest_cpu;
  3923. cpumask_t mask;
  3924. /* On same node? */
  3925. mask = node_to_cpumask(cpu_to_node(dead_cpu));
  3926. cpus_and(mask, mask, tsk->cpus_allowed);
  3927. dest_cpu = any_online_cpu(mask);
  3928. /* On any allowed CPU? */
  3929. if (dest_cpu == NR_CPUS)
  3930. dest_cpu = any_online_cpu(tsk->cpus_allowed);
  3931. /* No more Mr. Nice Guy. */
  3932. if (dest_cpu == NR_CPUS) {
  3933. cpus_setall(tsk->cpus_allowed);
  3934. dest_cpu = any_online_cpu(tsk->cpus_allowed);
  3935. /*
  3936. * Don't tell them about moving exiting tasks or
  3937. * kernel threads (both mm NULL), since they never
  3938. * leave kernel.
  3939. */
  3940. if (tsk->mm && printk_ratelimit())
  3941. printk(KERN_INFO "process %d (%s) no "
  3942. "longer affine to cpu%d\n",
  3943. tsk->pid, tsk->comm, dead_cpu);
  3944. }
  3945. __migrate_task(tsk, dead_cpu, dest_cpu);
  3946. }
  3947. /*
  3948. * While a dead CPU has no uninterruptible tasks queued at this point,
  3949. * it might still have a nonzero ->nr_uninterruptible counter, because
  3950. * for performance reasons the counter is not stricly tracking tasks to
  3951. * their home CPUs. So we just add the counter to another CPU's counter,
  3952. * to keep the global sum constant after CPU-down:
  3953. */
  3954. static void migrate_nr_uninterruptible(runqueue_t *rq_src)
  3955. {
  3956. runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
  3957. unsigned long flags;
  3958. local_irq_save(flags);
  3959. double_rq_lock(rq_src, rq_dest);
  3960. rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
  3961. rq_src->nr_uninterruptible = 0;
  3962. double_rq_unlock(rq_src, rq_dest);
  3963. local_irq_restore(flags);
  3964. }
  3965. /* Run through task list and migrate tasks from the dead cpu. */
  3966. static void migrate_live_tasks(int src_cpu)
  3967. {
  3968. struct task_struct *tsk, *t;
  3969. write_lock_irq(&tasklist_lock);
  3970. do_each_thread(t, tsk) {
  3971. if (tsk == current)
  3972. continue;
  3973. if (task_cpu(tsk) == src_cpu)
  3974. move_task_off_dead_cpu(src_cpu, tsk);
  3975. } while_each_thread(t, tsk);
  3976. write_unlock_irq(&tasklist_lock);
  3977. }
  3978. /* Schedules idle task to be the next runnable task on current CPU.
  3979. * It does so by boosting its priority to highest possible and adding it to
  3980. * the _front_ of runqueue. Used by CPU offline code.
  3981. */
  3982. void sched_idle_next(void)
  3983. {
  3984. int cpu = smp_processor_id();
  3985. runqueue_t *rq = this_rq();
  3986. struct task_struct *p = rq->idle;
  3987. unsigned long flags;
  3988. /* cpu has to be offline */
  3989. BUG_ON(cpu_online(cpu));
  3990. /* Strictly not necessary since rest of the CPUs are stopped by now
  3991. * and interrupts disabled on current cpu.
  3992. */
  3993. spin_lock_irqsave(&rq->lock, flags);
  3994. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  3995. /* Add idle task to _front_ of it's priority queue */
  3996. __activate_idle_task(p, rq);
  3997. spin_unlock_irqrestore(&rq->lock, flags);
  3998. }
  3999. /* Ensures that the idle task is using init_mm right before its cpu goes
  4000. * offline.
  4001. */
  4002. void idle_task_exit(void)
  4003. {
  4004. struct mm_struct *mm = current->active_mm;
  4005. BUG_ON(cpu_online(smp_processor_id()));
  4006. if (mm != &init_mm)
  4007. switch_mm(mm, &init_mm, current);
  4008. mmdrop(mm);
  4009. }
  4010. static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
  4011. {
  4012. struct runqueue *rq = cpu_rq(dead_cpu);
  4013. /* Must be exiting, otherwise would be on tasklist. */
  4014. BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
  4015. /* Cannot have done final schedule yet: would have vanished. */
  4016. BUG_ON(tsk->flags & PF_DEAD);
  4017. get_task_struct(tsk);
  4018. /*
  4019. * Drop lock around migration; if someone else moves it,
  4020. * that's OK. No task can be added to this CPU, so iteration is
  4021. * fine.
  4022. */
  4023. spin_unlock_irq(&rq->lock);
  4024. move_task_off_dead_cpu(dead_cpu, tsk);
  4025. spin_lock_irq(&rq->lock);
  4026. put_task_struct(tsk);
  4027. }
  4028. /* release_task() removes task from tasklist, so we won't find dead tasks. */
  4029. static void migrate_dead_tasks(unsigned int dead_cpu)
  4030. {
  4031. unsigned arr, i;
  4032. struct runqueue *rq = cpu_rq(dead_cpu);
  4033. for (arr = 0; arr < 2; arr++) {
  4034. for (i = 0; i < MAX_PRIO; i++) {
  4035. struct list_head *list = &rq->arrays[arr].queue[i];
  4036. while (!list_empty(list))
  4037. migrate_dead(dead_cpu,
  4038. list_entry(list->next, task_t,
  4039. run_list));
  4040. }
  4041. }
  4042. }
  4043. #endif /* CONFIG_HOTPLUG_CPU */
  4044. /*
  4045. * migration_call - callback that gets triggered when a CPU is added.
  4046. * Here we can start up the necessary migration thread for the new CPU.
  4047. */
  4048. static int migration_call(struct notifier_block *nfb, unsigned long action,
  4049. void *hcpu)
  4050. {
  4051. int cpu = (long)hcpu;
  4052. struct task_struct *p;
  4053. struct runqueue *rq;
  4054. unsigned long flags;
  4055. switch (action) {
  4056. case CPU_UP_PREPARE:
  4057. p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
  4058. if (IS_ERR(p))
  4059. return NOTIFY_BAD;
  4060. p->flags |= PF_NOFREEZE;
  4061. kthread_bind(p, cpu);
  4062. /* Must be high prio: stop_machine expects to yield to it. */
  4063. rq = task_rq_lock(p, &flags);
  4064. __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
  4065. task_rq_unlock(rq, &flags);
  4066. cpu_rq(cpu)->migration_thread = p;
  4067. break;
  4068. case CPU_ONLINE:
  4069. /* Strictly unneccessary, as first user will wake it. */
  4070. wake_up_process(cpu_rq(cpu)->migration_thread);
  4071. break;
  4072. #ifdef CONFIG_HOTPLUG_CPU
  4073. case CPU_UP_CANCELED:
  4074. /* Unbind it from offline cpu so it can run. Fall thru. */
  4075. kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
  4076. kthread_stop(cpu_rq(cpu)->migration_thread);
  4077. cpu_rq(cpu)->migration_thread = NULL;
  4078. break;
  4079. case CPU_DEAD:
  4080. migrate_live_tasks(cpu);
  4081. rq = cpu_rq(cpu);
  4082. kthread_stop(rq->migration_thread);
  4083. rq->migration_thread = NULL;
  4084. /* Idle task back to normal (off runqueue, low prio) */
  4085. rq = task_rq_lock(rq->idle, &flags);
  4086. deactivate_task(rq->idle, rq);
  4087. rq->idle->static_prio = MAX_PRIO;
  4088. __setscheduler(rq->idle, SCHED_NORMAL, 0);
  4089. migrate_dead_tasks(cpu);
  4090. task_rq_unlock(rq, &flags);
  4091. migrate_nr_uninterruptible(rq);
  4092. BUG_ON(rq->nr_running != 0);
  4093. /* No need to migrate the tasks: it was best-effort if
  4094. * they didn't do lock_cpu_hotplug(). Just wake up
  4095. * the requestors. */
  4096. spin_lock_irq(&rq->lock);
  4097. while (!list_empty(&rq->migration_queue)) {
  4098. migration_req_t *req;
  4099. req = list_entry(rq->migration_queue.next,
  4100. migration_req_t, list);
  4101. list_del_init(&req->list);
  4102. complete(&req->done);
  4103. }
  4104. spin_unlock_irq(&rq->lock);
  4105. break;
  4106. #endif
  4107. }
  4108. return NOTIFY_OK;
  4109. }
  4110. /* Register at highest priority so that task migration (migrate_all_tasks)
  4111. * happens before everything else.
  4112. */
  4113. static struct notifier_block __devinitdata migration_notifier = {
  4114. .notifier_call = migration_call,
  4115. .priority = 10
  4116. };
  4117. int __init migration_init(void)
  4118. {
  4119. void *cpu = (void *)(long)smp_processor_id();
  4120. /* Start one for boot CPU. */
  4121. migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
  4122. migration_call(&migration_notifier, CPU_ONLINE, cpu);
  4123. register_cpu_notifier(&migration_notifier);
  4124. return 0;
  4125. }
  4126. #endif
  4127. #ifdef CONFIG_SMP
  4128. #undef SCHED_DOMAIN_DEBUG
  4129. #ifdef SCHED_DOMAIN_DEBUG
  4130. static void sched_domain_debug(struct sched_domain *sd, int cpu)
  4131. {
  4132. int level = 0;
  4133. if (!sd) {
  4134. printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
  4135. return;
  4136. }
  4137. printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
  4138. do {
  4139. int i;
  4140. char str[NR_CPUS];
  4141. struct sched_group *group = sd->groups;
  4142. cpumask_t groupmask;
  4143. cpumask_scnprintf(str, NR_CPUS, sd->span);
  4144. cpus_clear(groupmask);
  4145. printk(KERN_DEBUG);
  4146. for (i = 0; i < level + 1; i++)
  4147. printk(" ");
  4148. printk("domain %d: ", level);
  4149. if (!(sd->flags & SD_LOAD_BALANCE)) {
  4150. printk("does not load-balance\n");
  4151. if (sd->parent)
  4152. printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
  4153. break;
  4154. }
  4155. printk("span %s\n", str);
  4156. if (!cpu_isset(cpu, sd->span))
  4157. printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
  4158. if (!cpu_isset(cpu, group->cpumask))
  4159. printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
  4160. printk(KERN_DEBUG);
  4161. for (i = 0; i < level + 2; i++)
  4162. printk(" ");
  4163. printk("groups:");
  4164. do {
  4165. if (!group) {
  4166. printk("\n");
  4167. printk(KERN_ERR "ERROR: group is NULL\n");
  4168. break;
  4169. }
  4170. if (!group->cpu_power) {
  4171. printk("\n");
  4172. printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
  4173. }
  4174. if (!cpus_weight(group->cpumask)) {
  4175. printk("\n");
  4176. printk(KERN_ERR "ERROR: empty group\n");
  4177. }
  4178. if (cpus_intersects(groupmask, group->cpumask)) {
  4179. printk("\n");
  4180. printk(KERN_ERR "ERROR: repeated CPUs\n");
  4181. }
  4182. cpus_or(groupmask, groupmask, group->cpumask);
  4183. cpumask_scnprintf(str, NR_CPUS, group->cpumask);
  4184. printk(" %s", str);
  4185. group = group->next;
  4186. } while (group != sd->groups);
  4187. printk("\n");
  4188. if (!cpus_equal(sd->span, groupmask))
  4189. printk(KERN_ERR "ERROR: groups don't span domain->span\n");
  4190. level++;
  4191. sd = sd->parent;
  4192. if (sd) {
  4193. if (!cpus_subset(groupmask, sd->span))
  4194. printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
  4195. }
  4196. } while (sd);
  4197. }
  4198. #else
  4199. #define sched_domain_debug(sd, cpu) {}
  4200. #endif
  4201. static int sd_degenerate(struct sched_domain *sd)
  4202. {
  4203. if (cpus_weight(sd->span) == 1)
  4204. return 1;
  4205. /* Following flags need at least 2 groups */
  4206. if (sd->flags & (SD_LOAD_BALANCE |
  4207. SD_BALANCE_NEWIDLE |
  4208. SD_BALANCE_FORK |
  4209. SD_BALANCE_EXEC)) {
  4210. if (sd->groups != sd->groups->next)
  4211. return 0;
  4212. }
  4213. /* Following flags don't use groups */
  4214. if (sd->flags & (SD_WAKE_IDLE |
  4215. SD_WAKE_AFFINE |
  4216. SD_WAKE_BALANCE))
  4217. return 0;
  4218. return 1;
  4219. }
  4220. static int sd_parent_degenerate(struct sched_domain *sd,
  4221. struct sched_domain *parent)
  4222. {
  4223. unsigned long cflags = sd->flags, pflags = parent->flags;
  4224. if (sd_degenerate(parent))
  4225. return 1;
  4226. if (!cpus_equal(sd->span, parent->span))
  4227. return 0;
  4228. /* Does parent contain flags not in child? */
  4229. /* WAKE_BALANCE is a subset of WAKE_AFFINE */
  4230. if (cflags & SD_WAKE_AFFINE)
  4231. pflags &= ~SD_WAKE_BALANCE;
  4232. /* Flags needing groups don't count if only 1 group in parent */
  4233. if (parent->groups == parent->groups->next) {
  4234. pflags &= ~(SD_LOAD_BALANCE |
  4235. SD_BALANCE_NEWIDLE |
  4236. SD_BALANCE_FORK |
  4237. SD_BALANCE_EXEC);
  4238. }
  4239. if (~cflags & pflags)
  4240. return 0;
  4241. return 1;
  4242. }
  4243. /*
  4244. * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
  4245. * hold the hotplug lock.
  4246. */
  4247. static void cpu_attach_domain(struct sched_domain *sd, int cpu)
  4248. {
  4249. runqueue_t *rq = cpu_rq(cpu);
  4250. struct sched_domain *tmp;
  4251. /* Remove the sched domains which do not contribute to scheduling. */
  4252. for (tmp = sd; tmp; tmp = tmp->parent) {
  4253. struct sched_domain *parent = tmp->parent;
  4254. if (!parent)
  4255. break;
  4256. if (sd_parent_degenerate(tmp, parent))
  4257. tmp->parent = parent->parent;
  4258. }
  4259. if (sd && sd_degenerate(sd))
  4260. sd = sd->parent;
  4261. sched_domain_debug(sd, cpu);
  4262. rcu_assign_pointer(rq->sd, sd);
  4263. }
  4264. /* cpus with isolated domains */
  4265. static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
  4266. /* Setup the mask of cpus configured for isolated domains */
  4267. static int __init isolated_cpu_setup(char *str)
  4268. {
  4269. int ints[NR_CPUS], i;
  4270. str = get_options(str, ARRAY_SIZE(ints), ints);
  4271. cpus_clear(cpu_isolated_map);
  4272. for (i = 1; i <= ints[0]; i++)
  4273. if (ints[i] < NR_CPUS)
  4274. cpu_set(ints[i], cpu_isolated_map);
  4275. return 1;
  4276. }
  4277. __setup ("isolcpus=", isolated_cpu_setup);
  4278. /*
  4279. * init_sched_build_groups takes an array of groups, the cpumask we wish
  4280. * to span, and a pointer to a function which identifies what group a CPU
  4281. * belongs to. The return value of group_fn must be a valid index into the
  4282. * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
  4283. * keep track of groups covered with a cpumask_t).
  4284. *
  4285. * init_sched_build_groups will build a circular linked list of the groups
  4286. * covered by the given span, and will set each group's ->cpumask correctly,
  4287. * and ->cpu_power to 0.
  4288. */
  4289. static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
  4290. int (*group_fn)(int cpu))
  4291. {
  4292. struct sched_group *first = NULL, *last = NULL;
  4293. cpumask_t covered = CPU_MASK_NONE;
  4294. int i;
  4295. for_each_cpu_mask(i, span) {
  4296. int group = group_fn(i);
  4297. struct sched_group *sg = &groups[group];
  4298. int j;
  4299. if (cpu_isset(i, covered))
  4300. continue;
  4301. sg->cpumask = CPU_MASK_NONE;
  4302. sg->cpu_power = 0;
  4303. for_each_cpu_mask(j, span) {
  4304. if (group_fn(j) != group)
  4305. continue;
  4306. cpu_set(j, covered);
  4307. cpu_set(j, sg->cpumask);
  4308. }
  4309. if (!first)
  4310. first = sg;
  4311. if (last)
  4312. last->next = sg;
  4313. last = sg;
  4314. }
  4315. last->next = first;
  4316. }
  4317. #define SD_NODES_PER_DOMAIN 16
  4318. #ifdef CONFIG_NUMA
  4319. /**
  4320. * find_next_best_node - find the next node to include in a sched_domain
  4321. * @node: node whose sched_domain we're building
  4322. * @used_nodes: nodes already in the sched_domain
  4323. *
  4324. * Find the next node to include in a given scheduling domain. Simply
  4325. * finds the closest node not already in the @used_nodes map.
  4326. *
  4327. * Should use nodemask_t.
  4328. */
  4329. static int find_next_best_node(int node, unsigned long *used_nodes)
  4330. {
  4331. int i, n, val, min_val, best_node = 0;
  4332. min_val = INT_MAX;
  4333. for (i = 0; i < MAX_NUMNODES; i++) {
  4334. /* Start at @node */
  4335. n = (node + i) % MAX_NUMNODES;
  4336. if (!nr_cpus_node(n))
  4337. continue;
  4338. /* Skip already used nodes */
  4339. if (test_bit(n, used_nodes))
  4340. continue;
  4341. /* Simple min distance search */
  4342. val = node_distance(node, n);
  4343. if (val < min_val) {
  4344. min_val = val;
  4345. best_node = n;
  4346. }
  4347. }
  4348. set_bit(best_node, used_nodes);
  4349. return best_node;
  4350. }
  4351. /**
  4352. * sched_domain_node_span - get a cpumask for a node's sched_domain
  4353. * @node: node whose cpumask we're constructing
  4354. * @size: number of nodes to include in this span
  4355. *
  4356. * Given a node, construct a good cpumask for its sched_domain to span. It
  4357. * should be one that prevents unnecessary balancing, but also spreads tasks
  4358. * out optimally.
  4359. */
  4360. static cpumask_t sched_domain_node_span(int node)
  4361. {
  4362. int i;
  4363. cpumask_t span, nodemask;
  4364. DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
  4365. cpus_clear(span);
  4366. bitmap_zero(used_nodes, MAX_NUMNODES);
  4367. nodemask = node_to_cpumask(node);
  4368. cpus_or(span, span, nodemask);
  4369. set_bit(node, used_nodes);
  4370. for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
  4371. int next_node = find_next_best_node(node, used_nodes);
  4372. nodemask = node_to_cpumask(next_node);
  4373. cpus_or(span, span, nodemask);
  4374. }
  4375. return span;
  4376. }
  4377. #endif
  4378. /*
  4379. * At the moment, CONFIG_SCHED_SMT is never defined, but leave it in so we
  4380. * can switch it on easily if needed.
  4381. */
  4382. #ifdef CONFIG_SCHED_SMT
  4383. static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
  4384. static struct sched_group sched_group_cpus[NR_CPUS];
  4385. static int cpu_to_cpu_group(int cpu)
  4386. {
  4387. return cpu;
  4388. }
  4389. #endif
  4390. static DEFINE_PER_CPU(struct sched_domain, phys_domains);
  4391. static struct sched_group sched_group_phys[NR_CPUS];
  4392. static int cpu_to_phys_group(int cpu)
  4393. {
  4394. #ifdef CONFIG_SCHED_SMT
  4395. return first_cpu(cpu_sibling_map[cpu]);
  4396. #else
  4397. return cpu;
  4398. #endif
  4399. }
  4400. #ifdef CONFIG_NUMA
  4401. /*
  4402. * The init_sched_build_groups can't handle what we want to do with node
  4403. * groups, so roll our own. Now each node has its own list of groups which
  4404. * gets dynamically allocated.
  4405. */
  4406. static DEFINE_PER_CPU(struct sched_domain, node_domains);
  4407. static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
  4408. static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
  4409. static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
  4410. static int cpu_to_allnodes_group(int cpu)
  4411. {
  4412. return cpu_to_node(cpu);
  4413. }
  4414. #endif
  4415. /*
  4416. * Build sched domains for a given set of cpus and attach the sched domains
  4417. * to the individual cpus
  4418. */
  4419. void build_sched_domains(const cpumask_t *cpu_map)
  4420. {
  4421. int i;
  4422. #ifdef CONFIG_NUMA
  4423. struct sched_group **sched_group_nodes = NULL;
  4424. struct sched_group *sched_group_allnodes = NULL;
  4425. /*
  4426. * Allocate the per-node list of sched groups
  4427. */
  4428. sched_group_nodes = kmalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
  4429. GFP_ATOMIC);
  4430. if (!sched_group_nodes) {
  4431. printk(KERN_WARNING "Can not alloc sched group node list\n");
  4432. return;
  4433. }
  4434. sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
  4435. #endif
  4436. /*
  4437. * Set up domains for cpus specified by the cpu_map.
  4438. */
  4439. for_each_cpu_mask(i, *cpu_map) {
  4440. int group;
  4441. struct sched_domain *sd = NULL, *p;
  4442. cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
  4443. cpus_and(nodemask, nodemask, *cpu_map);
  4444. #ifdef CONFIG_NUMA
  4445. if (cpus_weight(*cpu_map)
  4446. > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
  4447. if (!sched_group_allnodes) {
  4448. sched_group_allnodes
  4449. = kmalloc(sizeof(struct sched_group)
  4450. * MAX_NUMNODES,
  4451. GFP_KERNEL);
  4452. if (!sched_group_allnodes) {
  4453. printk(KERN_WARNING
  4454. "Can not alloc allnodes sched group\n");
  4455. break;
  4456. }
  4457. sched_group_allnodes_bycpu[i]
  4458. = sched_group_allnodes;
  4459. }
  4460. sd = &per_cpu(allnodes_domains, i);
  4461. *sd = SD_ALLNODES_INIT;
  4462. sd->span = *cpu_map;
  4463. group = cpu_to_allnodes_group(i);
  4464. sd->groups = &sched_group_allnodes[group];
  4465. p = sd;
  4466. } else
  4467. p = NULL;
  4468. sd = &per_cpu(node_domains, i);
  4469. *sd = SD_NODE_INIT;
  4470. sd->span = sched_domain_node_span(cpu_to_node(i));
  4471. sd->parent = p;
  4472. cpus_and(sd->span, sd->span, *cpu_map);
  4473. #endif
  4474. p = sd;
  4475. sd = &per_cpu(phys_domains, i);
  4476. group = cpu_to_phys_group(i);
  4477. *sd = SD_CPU_INIT;
  4478. sd->span = nodemask;
  4479. sd->parent = p;
  4480. sd->groups = &sched_group_phys[group];
  4481. #ifdef CONFIG_SCHED_SMT
  4482. p = sd;
  4483. sd = &per_cpu(cpu_domains, i);
  4484. group = cpu_to_cpu_group(i);
  4485. *sd = SD_SIBLING_INIT;
  4486. sd->span = cpu_sibling_map[i];
  4487. cpus_and(sd->span, sd->span, *cpu_map);
  4488. sd->parent = p;
  4489. sd->groups = &sched_group_cpus[group];
  4490. #endif
  4491. }
  4492. #ifdef CONFIG_SCHED_SMT
  4493. /* Set up CPU (sibling) groups */
  4494. for_each_cpu_mask(i, *cpu_map) {
  4495. cpumask_t this_sibling_map = cpu_sibling_map[i];
  4496. cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
  4497. if (i != first_cpu(this_sibling_map))
  4498. continue;
  4499. init_sched_build_groups(sched_group_cpus, this_sibling_map,
  4500. &cpu_to_cpu_group);
  4501. }
  4502. #endif
  4503. /* Set up physical groups */
  4504. for (i = 0; i < MAX_NUMNODES; i++) {
  4505. cpumask_t nodemask = node_to_cpumask(i);
  4506. cpus_and(nodemask, nodemask, *cpu_map);
  4507. if (cpus_empty(nodemask))
  4508. continue;
  4509. init_sched_build_groups(sched_group_phys, nodemask,
  4510. &cpu_to_phys_group);
  4511. }
  4512. #ifdef CONFIG_NUMA
  4513. /* Set up node groups */
  4514. if (sched_group_allnodes)
  4515. init_sched_build_groups(sched_group_allnodes, *cpu_map,
  4516. &cpu_to_allnodes_group);
  4517. for (i = 0; i < MAX_NUMNODES; i++) {
  4518. /* Set up node groups */
  4519. struct sched_group *sg, *prev;
  4520. cpumask_t nodemask = node_to_cpumask(i);
  4521. cpumask_t domainspan;
  4522. cpumask_t covered = CPU_MASK_NONE;
  4523. int j;
  4524. cpus_and(nodemask, nodemask, *cpu_map);
  4525. if (cpus_empty(nodemask)) {
  4526. sched_group_nodes[i] = NULL;
  4527. continue;
  4528. }
  4529. domainspan = sched_domain_node_span(i);
  4530. cpus_and(domainspan, domainspan, *cpu_map);
  4531. sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
  4532. sched_group_nodes[i] = sg;
  4533. for_each_cpu_mask(j, nodemask) {
  4534. struct sched_domain *sd;
  4535. sd = &per_cpu(node_domains, j);
  4536. sd->groups = sg;
  4537. if (sd->groups == NULL) {
  4538. /* Turn off balancing if we have no groups */
  4539. sd->flags = 0;
  4540. }
  4541. }
  4542. if (!sg) {
  4543. printk(KERN_WARNING
  4544. "Can not alloc domain group for node %d\n", i);
  4545. continue;
  4546. }
  4547. sg->cpu_power = 0;
  4548. sg->cpumask = nodemask;
  4549. cpus_or(covered, covered, nodemask);
  4550. prev = sg;
  4551. for (j = 0; j < MAX_NUMNODES; j++) {
  4552. cpumask_t tmp, notcovered;
  4553. int n = (i + j) % MAX_NUMNODES;
  4554. cpus_complement(notcovered, covered);
  4555. cpus_and(tmp, notcovered, *cpu_map);
  4556. cpus_and(tmp, tmp, domainspan);
  4557. if (cpus_empty(tmp))
  4558. break;
  4559. nodemask = node_to_cpumask(n);
  4560. cpus_and(tmp, tmp, nodemask);
  4561. if (cpus_empty(tmp))
  4562. continue;
  4563. sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
  4564. if (!sg) {
  4565. printk(KERN_WARNING
  4566. "Can not alloc domain group for node %d\n", j);
  4567. break;
  4568. }
  4569. sg->cpu_power = 0;
  4570. sg->cpumask = tmp;
  4571. cpus_or(covered, covered, tmp);
  4572. prev->next = sg;
  4573. prev = sg;
  4574. }
  4575. prev->next = sched_group_nodes[i];
  4576. }
  4577. #endif
  4578. /* Calculate CPU power for physical packages and nodes */
  4579. for_each_cpu_mask(i, *cpu_map) {
  4580. int power;
  4581. struct sched_domain *sd;
  4582. #ifdef CONFIG_SCHED_SMT
  4583. sd = &per_cpu(cpu_domains, i);
  4584. power = SCHED_LOAD_SCALE;
  4585. sd->groups->cpu_power = power;
  4586. #endif
  4587. sd = &per_cpu(phys_domains, i);
  4588. power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
  4589. (cpus_weight(sd->groups->cpumask)-1) / 10;
  4590. sd->groups->cpu_power = power;
  4591. #ifdef CONFIG_NUMA
  4592. sd = &per_cpu(allnodes_domains, i);
  4593. if (sd->groups) {
  4594. power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
  4595. (cpus_weight(sd->groups->cpumask)-1) / 10;
  4596. sd->groups->cpu_power = power;
  4597. }
  4598. #endif
  4599. }
  4600. #ifdef CONFIG_NUMA
  4601. for (i = 0; i < MAX_NUMNODES; i++) {
  4602. struct sched_group *sg = sched_group_nodes[i];
  4603. int j;
  4604. if (sg == NULL)
  4605. continue;
  4606. next_sg:
  4607. for_each_cpu_mask(j, sg->cpumask) {
  4608. struct sched_domain *sd;
  4609. int power;
  4610. sd = &per_cpu(phys_domains, j);
  4611. if (j != first_cpu(sd->groups->cpumask)) {
  4612. /*
  4613. * Only add "power" once for each
  4614. * physical package.
  4615. */
  4616. continue;
  4617. }
  4618. power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
  4619. (cpus_weight(sd->groups->cpumask)-1) / 10;
  4620. sg->cpu_power += power;
  4621. }
  4622. sg = sg->next;
  4623. if (sg != sched_group_nodes[i])
  4624. goto next_sg;
  4625. }
  4626. #endif
  4627. /* Attach the domains */
  4628. for_each_cpu_mask(i, *cpu_map) {
  4629. struct sched_domain *sd;
  4630. #ifdef CONFIG_SCHED_SMT
  4631. sd = &per_cpu(cpu_domains, i);
  4632. #else
  4633. sd = &per_cpu(phys_domains, i);
  4634. #endif
  4635. cpu_attach_domain(sd, i);
  4636. }
  4637. }
  4638. /*
  4639. * Set up scheduler domains and groups. Callers must hold the hotplug lock.
  4640. */
  4641. static void arch_init_sched_domains(const cpumask_t *cpu_map)
  4642. {
  4643. cpumask_t cpu_default_map;
  4644. /*
  4645. * Setup mask for cpus without special case scheduling requirements.
  4646. * For now this just excludes isolated cpus, but could be used to
  4647. * exclude other special cases in the future.
  4648. */
  4649. cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
  4650. build_sched_domains(&cpu_default_map);
  4651. }
  4652. static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
  4653. {
  4654. #ifdef CONFIG_NUMA
  4655. int i;
  4656. int cpu;
  4657. for_each_cpu_mask(cpu, *cpu_map) {
  4658. struct sched_group *sched_group_allnodes
  4659. = sched_group_allnodes_bycpu[cpu];
  4660. struct sched_group **sched_group_nodes
  4661. = sched_group_nodes_bycpu[cpu];
  4662. if (sched_group_allnodes) {
  4663. kfree(sched_group_allnodes);
  4664. sched_group_allnodes_bycpu[cpu] = NULL;
  4665. }
  4666. if (!sched_group_nodes)
  4667. continue;
  4668. for (i = 0; i < MAX_NUMNODES; i++) {
  4669. cpumask_t nodemask = node_to_cpumask(i);
  4670. struct sched_group *oldsg, *sg = sched_group_nodes[i];
  4671. cpus_and(nodemask, nodemask, *cpu_map);
  4672. if (cpus_empty(nodemask))
  4673. continue;
  4674. if (sg == NULL)
  4675. continue;
  4676. sg = sg->next;
  4677. next_sg:
  4678. oldsg = sg;
  4679. sg = sg->next;
  4680. kfree(oldsg);
  4681. if (oldsg != sched_group_nodes[i])
  4682. goto next_sg;
  4683. }
  4684. kfree(sched_group_nodes);
  4685. sched_group_nodes_bycpu[cpu] = NULL;
  4686. }
  4687. #endif
  4688. }
  4689. /*
  4690. * Detach sched domains from a group of cpus specified in cpu_map
  4691. * These cpus will now be attached to the NULL domain
  4692. */
  4693. static inline void detach_destroy_domains(const cpumask_t *cpu_map)
  4694. {
  4695. int i;
  4696. for_each_cpu_mask(i, *cpu_map)
  4697. cpu_attach_domain(NULL, i);
  4698. synchronize_sched();
  4699. arch_destroy_sched_domains(cpu_map);
  4700. }
  4701. /*
  4702. * Partition sched domains as specified by the cpumasks below.
  4703. * This attaches all cpus from the cpumasks to the NULL domain,
  4704. * waits for a RCU quiescent period, recalculates sched
  4705. * domain information and then attaches them back to the
  4706. * correct sched domains
  4707. * Call with hotplug lock held
  4708. */
  4709. void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
  4710. {
  4711. cpumask_t change_map;
  4712. cpus_and(*partition1, *partition1, cpu_online_map);
  4713. cpus_and(*partition2, *partition2, cpu_online_map);
  4714. cpus_or(change_map, *partition1, *partition2);
  4715. /* Detach sched domains from all of the affected cpus */
  4716. detach_destroy_domains(&change_map);
  4717. if (!cpus_empty(*partition1))
  4718. build_sched_domains(partition1);
  4719. if (!cpus_empty(*partition2))
  4720. build_sched_domains(partition2);
  4721. }
  4722. #ifdef CONFIG_HOTPLUG_CPU
  4723. /*
  4724. * Force a reinitialization of the sched domains hierarchy. The domains
  4725. * and groups cannot be updated in place without racing with the balancing
  4726. * code, so we temporarily attach all running cpus to the NULL domain
  4727. * which will prevent rebalancing while the sched domains are recalculated.
  4728. */
  4729. static int update_sched_domains(struct notifier_block *nfb,
  4730. unsigned long action, void *hcpu)
  4731. {
  4732. switch (action) {
  4733. case CPU_UP_PREPARE:
  4734. case CPU_DOWN_PREPARE:
  4735. detach_destroy_domains(&cpu_online_map);
  4736. return NOTIFY_OK;
  4737. case CPU_UP_CANCELED:
  4738. case CPU_DOWN_FAILED:
  4739. case CPU_ONLINE:
  4740. case CPU_DEAD:
  4741. /*
  4742. * Fall through and re-initialise the domains.
  4743. */
  4744. break;
  4745. default:
  4746. return NOTIFY_DONE;
  4747. }
  4748. /* The hotplug lock is already held by cpu_up/cpu_down */
  4749. arch_init_sched_domains(&cpu_online_map);
  4750. return NOTIFY_OK;
  4751. }
  4752. #endif
  4753. void __init sched_init_smp(void)
  4754. {
  4755. lock_cpu_hotplug();
  4756. arch_init_sched_domains(&cpu_online_map);
  4757. unlock_cpu_hotplug();
  4758. /* XXX: Theoretical race here - CPU may be hotplugged now */
  4759. hotcpu_notifier(update_sched_domains, 0);
  4760. }
  4761. #else
  4762. void __init sched_init_smp(void)
  4763. {
  4764. }
  4765. #endif /* CONFIG_SMP */
  4766. int in_sched_functions(unsigned long addr)
  4767. {
  4768. /* Linker adds these: start and end of __sched functions */
  4769. extern char __sched_text_start[], __sched_text_end[];
  4770. return in_lock_functions(addr) ||
  4771. (addr >= (unsigned long)__sched_text_start
  4772. && addr < (unsigned long)__sched_text_end);
  4773. }
  4774. void __init sched_init(void)
  4775. {
  4776. runqueue_t *rq;
  4777. int i, j, k;
  4778. for (i = 0; i < NR_CPUS; i++) {
  4779. prio_array_t *array;
  4780. rq = cpu_rq(i);
  4781. spin_lock_init(&rq->lock);
  4782. rq->nr_running = 0;
  4783. rq->active = rq->arrays;
  4784. rq->expired = rq->arrays + 1;
  4785. rq->best_expired_prio = MAX_PRIO;
  4786. #ifdef CONFIG_SMP
  4787. rq->sd = NULL;
  4788. for (j = 1; j < 3; j++)
  4789. rq->cpu_load[j] = 0;
  4790. rq->active_balance = 0;
  4791. rq->push_cpu = 0;
  4792. rq->migration_thread = NULL;
  4793. INIT_LIST_HEAD(&rq->migration_queue);
  4794. #endif
  4795. atomic_set(&rq->nr_iowait, 0);
  4796. for (j = 0; j < 2; j++) {
  4797. array = rq->arrays + j;
  4798. for (k = 0; k < MAX_PRIO; k++) {
  4799. INIT_LIST_HEAD(array->queue + k);
  4800. __clear_bit(k, array->bitmap);
  4801. }
  4802. // delimiter for bitsearch
  4803. __set_bit(MAX_PRIO, array->bitmap);
  4804. }
  4805. }
  4806. /*
  4807. * The boot idle thread does lazy MMU switching as well:
  4808. */
  4809. atomic_inc(&init_mm.mm_count);
  4810. enter_lazy_tlb(&init_mm, current);
  4811. /*
  4812. * Make us the idle thread. Technically, schedule() should not be
  4813. * called from this thread, however somewhere below it might be,
  4814. * but because we are the idle thread, we just pick up running again
  4815. * when this runqueue becomes "idle".
  4816. */
  4817. init_idle(current, smp_processor_id());
  4818. }
  4819. #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
  4820. void __might_sleep(char *file, int line)
  4821. {
  4822. #if defined(in_atomic)
  4823. static unsigned long prev_jiffy; /* ratelimiting */
  4824. if ((in_atomic() || irqs_disabled()) &&
  4825. system_state == SYSTEM_RUNNING && !oops_in_progress) {
  4826. if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
  4827. return;
  4828. prev_jiffy = jiffies;
  4829. printk(KERN_ERR "Debug: sleeping function called from invalid"
  4830. " context at %s:%d\n", file, line);
  4831. printk("in_atomic():%d, irqs_disabled():%d\n",
  4832. in_atomic(), irqs_disabled());
  4833. dump_stack();
  4834. }
  4835. #endif
  4836. }
  4837. EXPORT_SYMBOL(__might_sleep);
  4838. #endif
  4839. #ifdef CONFIG_MAGIC_SYSRQ
  4840. void normalize_rt_tasks(void)
  4841. {
  4842. struct task_struct *p;
  4843. prio_array_t *array;
  4844. unsigned long flags;
  4845. runqueue_t *rq;
  4846. read_lock_irq(&tasklist_lock);
  4847. for_each_process (p) {
  4848. if (!rt_task(p))
  4849. continue;
  4850. rq = task_rq_lock(p, &flags);
  4851. array = p->array;
  4852. if (array)
  4853. deactivate_task(p, task_rq(p));
  4854. __setscheduler(p, SCHED_NORMAL, 0);
  4855. if (array) {
  4856. __activate_task(p, task_rq(p));
  4857. resched_task(rq->curr);
  4858. }
  4859. task_rq_unlock(rq, &flags);
  4860. }
  4861. read_unlock_irq(&tasklist_lock);
  4862. }
  4863. #endif /* CONFIG_MAGIC_SYSRQ */