sched.c 130 KB

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