main.c 133 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176
  1. /*
  2. * Copyright 2011 Con Kolivas
  3. * Copyright 2010 Jeff Garzik
  4. *
  5. * This program is free software; you can redistribute it and/or modify it
  6. * under the terms of the GNU General Public License as published by the Free
  7. * Software Foundation; either version 2 of the License, or (at your option)
  8. * any later version. See COPYING for more details.
  9. */
  10. #include "config.h"
  11. #include <curses.h>
  12. #include <stdio.h>
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <unistd.h>
  18. #include <sys/time.h>
  19. #include <time.h>
  20. #include <math.h>
  21. #include <stdarg.h>
  22. #include <assert.h>
  23. #include <signal.h>
  24. #ifndef WIN32
  25. #include <sys/resource.h>
  26. #endif
  27. #include <ccan/opt/opt.h>
  28. #include <jansson.h>
  29. #include <curl/curl.h>
  30. #include "compat.h"
  31. #include "miner.h"
  32. #include "findnonce.h"
  33. #include "bench_block.h"
  34. #include "ocl.h"
  35. #include "uthash.h"
  36. #include "adl.h"
  37. #if defined(unix)
  38. #include <errno.h>
  39. #include <fcntl.h>
  40. #include <unistd.h>
  41. #include <sys/wait.h>
  42. #include <sys/types.h>
  43. #endif
  44. #ifdef __linux /* Linux specific policy and affinity management */
  45. #include <sched.h>
  46. static inline void drop_policy(void)
  47. {
  48. struct sched_param param;
  49. #ifdef SCHED_BATCH
  50. #ifdef SCHED_IDLE
  51. if (unlikely(sched_setscheduler(0, SCHED_IDLE, &param) == -1))
  52. #endif
  53. sched_setscheduler(0, SCHED_BATCH, &param);
  54. #endif
  55. }
  56. static inline void affine_to_cpu(int id, int cpu)
  57. {
  58. cpu_set_t set;
  59. CPU_ZERO(&set);
  60. CPU_SET(cpu, &set);
  61. sched_setaffinity(0, sizeof(&set), &set);
  62. applog(LOG_INFO, "Binding cpu mining thread %d to cpu %d", id, cpu);
  63. }
  64. #else
  65. static inline void drop_policy(void)
  66. {
  67. }
  68. static inline void affine_to_cpu(int id, int cpu)
  69. {
  70. }
  71. #endif
  72. enum workio_commands {
  73. WC_GET_WORK,
  74. WC_SUBMIT_WORK,
  75. WC_DIE,
  76. };
  77. struct workio_cmd {
  78. enum workio_commands cmd;
  79. struct thr_info *thr;
  80. union {
  81. struct work *work;
  82. } u;
  83. bool lagging;
  84. };
  85. enum sha256_algos {
  86. ALGO_C, /* plain C */
  87. ALGO_4WAY, /* parallel SSE2 */
  88. ALGO_VIA, /* VIA padlock */
  89. ALGO_CRYPTOPP, /* Crypto++ (C) */
  90. ALGO_CRYPTOPP_ASM32, /* Crypto++ 32-bit assembly */
  91. ALGO_SSE2_32, /* SSE2 for x86_32 */
  92. ALGO_SSE2_64, /* SSE2 for x86_64 */
  93. ALGO_SSE4_64, /* SSE4 for x86_64 */
  94. };
  95. enum pool_strategy {
  96. POOL_FAILOVER,
  97. POOL_ROUNDROBIN,
  98. POOL_ROTATE,
  99. POOL_LOADBALANCE,
  100. };
  101. #define TOP_STRATEGY (POOL_LOADBALANCE)
  102. struct strategies {
  103. const char *s;
  104. } strategies[] = {
  105. { "Failover" },
  106. { "Round Robin" },
  107. { "Rotate" },
  108. { "Load Balance" },
  109. };
  110. static size_t max_name_len = 0;
  111. static char *name_spaces_pad = NULL;
  112. static const char *algo_names[] = {
  113. [ALGO_C] = "c",
  114. #ifdef WANT_SSE2_4WAY
  115. [ALGO_4WAY] = "4way",
  116. #endif
  117. #ifdef WANT_VIA_PADLOCK
  118. [ALGO_VIA] = "via",
  119. #endif
  120. [ALGO_CRYPTOPP] = "cryptopp",
  121. #ifdef WANT_CRYPTOPP_ASM32
  122. [ALGO_CRYPTOPP_ASM32] = "cryptopp_asm32",
  123. #endif
  124. #ifdef WANT_X8632_SSE2
  125. [ALGO_SSE2_32] = "sse2_32",
  126. #endif
  127. #ifdef WANT_X8664_SSE2
  128. [ALGO_SSE2_64] = "sse2_64",
  129. #endif
  130. #ifdef WANT_X8664_SSE4
  131. [ALGO_SSE4_64] = "sse4_64",
  132. #endif
  133. };
  134. typedef void (*sha256_func)();
  135. static const sha256_func sha256_funcs[] = {
  136. [ALGO_C] = (sha256_func)scanhash_c,
  137. #ifdef WANT_SSE2_4WAY
  138. [ALGO_4WAY] = (sha256_func)ScanHash_4WaySSE2,
  139. #endif
  140. #ifdef WANT_VIA_PADLOCK
  141. [ALGO_VIA] = (sha256_func)scanhash_via,
  142. #endif
  143. [ALGO_CRYPTOPP] = (sha256_func)scanhash_cryptopp,
  144. #ifdef WANT_CRYPTOPP_ASM32
  145. [ALGO_CRYPTOPP_ASM32] = (sha256_func)scanhash_asm32,
  146. #endif
  147. #ifdef WANT_X8632_SSE2
  148. [ALGO_SSE2_32] = (sha256_func)scanhash_sse2_32,
  149. #endif
  150. #ifdef WANT_X8664_SSE2
  151. [ALGO_SSE2_64] = (sha256_func)scanhash_sse2_64,
  152. #endif
  153. #ifdef WANT_X8664_SSE4
  154. [ALGO_SSE4_64] = (sha256_func)scanhash_sse4_64
  155. #endif
  156. };
  157. static char packagename[255];
  158. bool opt_debug = false;
  159. bool opt_protocol = false;
  160. static bool want_longpoll = true;
  161. static bool have_longpoll = false;
  162. static bool want_per_device_stats = false;
  163. bool use_syslog = false;
  164. static bool opt_quiet = false;
  165. static bool opt_realquiet = false;
  166. static bool opt_loginput = false;
  167. static int opt_retries = -1;
  168. static int opt_fail_pause = 5;
  169. static int fail_pause = 5;
  170. static int opt_log_interval = 5;
  171. bool opt_log_output = false;
  172. static bool opt_dynamic = true;
  173. static int opt_queue = 1;
  174. int opt_vectors;
  175. int opt_worksize;
  176. int opt_scantime = 60;
  177. int opt_bench_algo = -1;
  178. static const bool opt_time = true;
  179. static bool opt_restart = true;
  180. #if defined(WANT_X8664_SSE2) && defined(__SSE2__)
  181. static enum sha256_algos opt_algo = ALGO_SSE2_64;
  182. #elif defined(WANT_X8632_SSE2) && defined(__SSE2__)
  183. static enum sha256_algos opt_algo = ALGO_SSE2_32;
  184. #else
  185. static enum sha256_algos opt_algo = ALGO_C;
  186. #endif
  187. static int nDevs;
  188. static int opt_g_threads = 2;
  189. static int opt_device;
  190. static int total_devices;
  191. static bool gpu_devices[16];
  192. static int gpu_threads;
  193. static bool forced_n_threads;
  194. static int opt_n_threads;
  195. static int mining_threads;
  196. static int num_processors;
  197. static int scan_intensity;
  198. static bool use_curses = true;
  199. static bool opt_submit_stale;
  200. static bool opt_nogpu;
  201. static bool opt_usecpu;
  202. static int opt_shares;
  203. static bool opt_fail_only;
  204. char *opt_kernel_path;
  205. #define QUIET (opt_quiet || opt_realquiet)
  206. struct thr_info *thr_info;
  207. static int work_thr_id;
  208. int longpoll_thr_id;
  209. static int stage_thr_id;
  210. static int watchdog_thr_id;
  211. static int input_thr_id;
  212. static int gpur_thr_id;
  213. static int cpur_thr_id;
  214. static int total_threads;
  215. struct work_restart *work_restart = NULL;
  216. static pthread_mutex_t hash_lock;
  217. static pthread_mutex_t qd_lock;
  218. static pthread_mutex_t stgd_lock;
  219. static pthread_mutex_t curses_lock;
  220. static pthread_rwlock_t blk_lock;
  221. static double total_mhashes_done;
  222. static struct timeval total_tv_start, total_tv_end;
  223. pthread_mutex_t control_lock;
  224. int hw_errors;
  225. static int total_accepted, total_rejected;
  226. static int total_getworks, total_stale, total_discarded;
  227. static int total_queued;
  228. static unsigned int new_blocks;
  229. enum block_change {
  230. BLOCK_NONE,
  231. BLOCK_LP,
  232. BLOCK_DETECT,
  233. BLOCK_FIRST,
  234. };
  235. static enum block_change block_changed = BLOCK_FIRST;
  236. static unsigned int local_work;
  237. static unsigned int total_go, total_ro;
  238. #define MAX_POOLS (32)
  239. static struct pool *pools[MAX_POOLS];
  240. static struct pool *currentpool = NULL;
  241. static int total_pools;
  242. static enum pool_strategy pool_strategy = POOL_FAILOVER;
  243. static int opt_rotate_period;
  244. static int total_urls, total_users, total_passes, total_userpasses;
  245. static bool curses_active = false;
  246. static char current_block[37];
  247. static char *current_hash;
  248. static char datestamp[40];
  249. static char blocktime[30];
  250. struct block {
  251. char hash[37];
  252. UT_hash_handle hh;
  253. };
  254. static struct block *blocks = NULL;
  255. static char *opt_kernel = NULL;
  256. #if defined(unix)
  257. static char *opt_stderr_cmd = NULL;
  258. #endif // defined(unix)
  259. enum cl_kernel chosen_kernel;
  260. static bool ping = true;
  261. struct sigaction termhandler, inthandler;
  262. struct thread_q *getq;
  263. static int total_work;
  264. struct work *staged_work = NULL;
  265. struct schedtime {
  266. bool enable;
  267. struct tm tm;
  268. };
  269. struct schedtime schedstart;
  270. struct schedtime schedstop;
  271. bool sched_paused;
  272. static bool time_before(struct tm *tm1, struct tm *tm2)
  273. {
  274. if (tm1->tm_hour < tm2->tm_hour)
  275. return true;
  276. if (tm1->tm_hour == tm2->tm_hour && tm1->tm_min < tm2->tm_min)
  277. return true;
  278. return false;
  279. }
  280. static bool should_run(void)
  281. {
  282. struct timeval tv;
  283. struct tm tm;
  284. if (!schedstart.enable && !schedstop.enable)
  285. return true;
  286. gettimeofday(&tv, NULL);
  287. localtime_r(&tv.tv_sec, &tm);
  288. if (schedstart.enable) {
  289. if (!schedstop.enable) {
  290. if (time_before(&tm, &schedstart.tm))
  291. return false;
  292. /* This is a once off event with no stop time set */
  293. schedstart.enable = false;
  294. return true;
  295. }
  296. if (time_before(&schedstart.tm, &schedstop.tm)) {
  297. if (time_before(&tm, &schedstop.tm) && !time_before(&tm, &schedstart.tm))
  298. return true;
  299. return false;
  300. } /* Times are reversed */
  301. if (time_before(&tm, &schedstart.tm)) {
  302. if (time_before(&tm, &schedstop.tm))
  303. return true;
  304. return false;
  305. }
  306. return true;
  307. }
  308. /* only schedstop.enable == true */
  309. if (!time_before(&tm, &schedstop.tm))
  310. return false;
  311. return true;
  312. }
  313. void get_datestamp(char *f, struct timeval *tv)
  314. {
  315. struct tm tm;
  316. localtime_r(&tv->tv_sec, &tm);
  317. sprintf(f, "[%d-%02d-%02d %02d:%02d:%02d]",
  318. tm.tm_year + 1900,
  319. tm.tm_mon + 1,
  320. tm.tm_mday,
  321. tm.tm_hour,
  322. tm.tm_min,
  323. tm.tm_sec);
  324. }
  325. void get_timestamp(char *f, struct timeval *tv)
  326. {
  327. struct tm tm;
  328. localtime_r(&tv->tv_sec, &tm);
  329. sprintf(f, "[%02d:%02d:%02d]",
  330. tm.tm_hour,
  331. tm.tm_min,
  332. tm.tm_sec);
  333. }
  334. static void applog_and_exit(const char *fmt, ...)
  335. {
  336. va_list ap;
  337. va_start(ap, fmt);
  338. vapplog(LOG_ERR, fmt, ap);
  339. va_end(ap);
  340. exit(1);
  341. }
  342. static void add_pool(void)
  343. {
  344. struct pool *pool;
  345. pool = calloc(sizeof(struct pool), 1);
  346. if (!pool) {
  347. applog(LOG_ERR, "Failed to malloc pool in add_pool");
  348. exit (1);
  349. }
  350. pool->pool_no = pool->prio = total_pools;
  351. pools[total_pools++] = pool;
  352. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL))) {
  353. applog(LOG_ERR, "Failed to pthread_mutex_init in add_pool");
  354. exit (1);
  355. }
  356. /* Make sure the pool doesn't think we've been idle since time 0 */
  357. pool->tv_idle.tv_sec = ~0UL;
  358. }
  359. /* Pool variant of test and set */
  360. static bool pool_tset(struct pool *pool, bool *var)
  361. {
  362. bool ret;
  363. mutex_lock(&pool->pool_lock);
  364. ret = *var;
  365. *var = true;
  366. mutex_unlock(&pool->pool_lock);
  367. return ret;
  368. }
  369. static bool pool_tclear(struct pool *pool, bool *var)
  370. {
  371. bool ret;
  372. mutex_lock(&pool->pool_lock);
  373. ret = *var;
  374. *var = false;
  375. mutex_unlock(&pool->pool_lock);
  376. return ret;
  377. }
  378. static struct pool *current_pool(void)
  379. {
  380. struct pool *pool;
  381. mutex_lock(&control_lock);
  382. pool = currentpool;
  383. mutex_unlock(&control_lock);
  384. return pool;
  385. }
  386. // Algo benchmark, crash-prone, system independent stage
  387. static double bench_algo_stage3(
  388. enum sha256_algos algo
  389. )
  390. {
  391. // Use a random work block pulled from a pool
  392. static uint8_t bench_block[] = { CGMINER_BENCHMARK_BLOCK };
  393. struct work work __attribute__((aligned(128)));
  394. size_t bench_size = sizeof(work);
  395. size_t work_size = sizeof(bench_block);
  396. size_t min_size = (work_size < bench_size ? work_size : bench_size);
  397. memset(&work, 0, sizeof(work));
  398. memcpy(&work, &bench_block, min_size);
  399. struct work_restart dummy;
  400. work_restart = &dummy;
  401. struct timeval end;
  402. struct timeval start;
  403. uint32_t max_nonce = (1<<22);
  404. unsigned long hashes_done = 0;
  405. gettimeofday(&start, 0);
  406. #if defined(WANT_VIA_PADLOCK)
  407. // For some reason, the VIA padlock hasher has a different API ...
  408. if (ALGO_VIA==algo) {
  409. (void)scanhash_via(
  410. 0,
  411. work.data,
  412. work.target,
  413. max_nonce,
  414. &hashes_done,
  415. work.blk.nonce
  416. );
  417. } else
  418. #endif
  419. {
  420. sha256_func func = sha256_funcs[algo];
  421. (*func)(
  422. 0,
  423. work.midstate,
  424. work.data + 64,
  425. work.hash1,
  426. work.hash,
  427. work.target,
  428. max_nonce,
  429. &hashes_done,
  430. work.blk.nonce
  431. );
  432. }
  433. gettimeofday(&end, 0);
  434. work_restart = NULL;
  435. uint64_t usec_end = ((uint64_t)end.tv_sec)*1000*1000 + end.tv_usec;
  436. uint64_t usec_start = ((uint64_t)start.tv_sec)*1000*1000 + start.tv_usec;
  437. uint64_t usec_elapsed = usec_end - usec_start;
  438. double rate = -1.0;
  439. if (0<usec_elapsed) {
  440. rate = (1.0*hashes_done)/usec_elapsed;
  441. }
  442. return rate;
  443. }
  444. #if defined(unix)
  445. // Change non-blocking status on a file descriptor
  446. static void set_non_blocking(
  447. int fd,
  448. int yes
  449. )
  450. {
  451. int flags = fcntl(fd, F_GETFL, 0);
  452. if (flags<0) {
  453. perror("fcntl(GET) failed");
  454. exit(1);
  455. }
  456. flags = yes ? (flags|O_NONBLOCK) : (flags&~O_NONBLOCK);
  457. int r = fcntl(fd, F_SETFL, flags);
  458. if (r<0) {
  459. perror("fcntl(SET) failed");
  460. exit(1);
  461. }
  462. }
  463. #endif // defined(unix)
  464. // Algo benchmark, crash-safe, system-dependent stage
  465. static double bench_algo_stage2(
  466. enum sha256_algos algo
  467. )
  468. {
  469. // Here, the gig is to safely run a piece of code that potentially
  470. // crashes. Unfortunately, the Right Way (tm) to do this is rather
  471. // heavily platform dependent :(
  472. double rate = -1.23457;
  473. #if defined(unix)
  474. // Make a pipe: [readFD, writeFD]
  475. int pfd[2];
  476. int r = pipe(pfd);
  477. if (r<0) {
  478. perror("pipe - failed to create pipe for --algo auto");
  479. exit(1);
  480. }
  481. // Make pipe non blocking
  482. set_non_blocking(pfd[0], 1);
  483. set_non_blocking(pfd[1], 1);
  484. // Don't allow a crashing child to kill the main process
  485. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  486. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  487. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  488. perror("signal - failed to edit signal mask for --algo auto");
  489. exit(1);
  490. }
  491. // Fork a child to do the actual benchmarking
  492. pid_t child_pid = fork();
  493. if (child_pid<0) {
  494. perror("fork - failed to create a child process for --algo auto");
  495. exit(1);
  496. }
  497. // Do the dangerous work in the child, knowing we might crash
  498. if (0==child_pid) {
  499. // TODO: some umask trickery to prevent coredumps
  500. // Benchmark this algorithm
  501. double r = bench_algo_stage3(algo);
  502. // We survived, send result to parent and bail
  503. int loop_count = 0;
  504. while (1) {
  505. ssize_t bytes_written = write(pfd[1], &r, sizeof(r));
  506. int try_again = (0==bytes_written || (bytes_written<0 && EAGAIN==errno));
  507. int success = (sizeof(r)==(size_t)bytes_written);
  508. if (success)
  509. break;
  510. if (!try_again) {
  511. perror("write - child failed to write benchmark result to pipe");
  512. exit(1);
  513. }
  514. if (5<loop_count) {
  515. applog(LOG_ERR, "child tried %d times to communicate with parent, giving up", loop_count);
  516. exit(1);
  517. }
  518. ++loop_count;
  519. sleep(1);
  520. }
  521. exit(0);
  522. }
  523. // Parent waits for a result from child
  524. int loop_count = 0;
  525. while (1) {
  526. // Wait for child to die
  527. int status;
  528. int r = waitpid(child_pid, &status, WNOHANG);
  529. if ((child_pid==r) || (r<0 && ECHILD==errno)) {
  530. // Child died somehow. Grab result and bail
  531. double tmp;
  532. ssize_t bytes_read = read(pfd[0], &tmp, sizeof(tmp));
  533. if (sizeof(tmp)==(size_t)bytes_read)
  534. rate = tmp;
  535. break;
  536. } else if (r<0) {
  537. perror("bench_algo: waitpid failed. giving up.");
  538. exit(1);
  539. }
  540. // Give up on child after a ~60s
  541. if (60<loop_count) {
  542. kill(child_pid, SIGKILL);
  543. waitpid(child_pid, &status, 0);
  544. break;
  545. }
  546. // Wait a bit longer
  547. ++loop_count;
  548. sleep(1);
  549. }
  550. // Close pipe
  551. r = close(pfd[0]);
  552. if (r<0) {
  553. perror("close - failed to close read end of pipe for --algo auto");
  554. exit(1);
  555. }
  556. r = close(pfd[1]);
  557. if (r<0) {
  558. perror("close - failed to close read end of pipe for --algo auto");
  559. exit(1);
  560. }
  561. #elif defined(WIN32)
  562. // Get handle to current exe
  563. HINSTANCE module = GetModuleHandle(0);
  564. if (!module) {
  565. applog(LOG_ERR, "failed to retrieve module handle");
  566. exit(1);
  567. }
  568. // Create a unique name
  569. char unique_name[32];
  570. snprintf(
  571. unique_name,
  572. sizeof(unique_name)-1,
  573. "cgminer-%p",
  574. (void*)module
  575. );
  576. // Create and init a chunked of shared memory
  577. HANDLE map_handle = CreateFileMapping(
  578. INVALID_HANDLE_VALUE, // use paging file
  579. NULL, // default security attributes
  580. PAGE_READWRITE, // read/write access
  581. 0, // size: high 32-bits
  582. 4096, // size: low 32-bits
  583. unique_name // name of map object
  584. );
  585. if (NULL==map_handle) {
  586. applog(LOG_ERR, "could not create shared memory");
  587. exit(1);
  588. }
  589. void *shared_mem = MapViewOfFile(
  590. map_handle, // object to map view of
  591. FILE_MAP_WRITE, // read/write access
  592. 0, // high offset: map from
  593. 0, // low offset: beginning
  594. 0 // default: map entire file
  595. );
  596. if (NULL==shared_mem) {
  597. applog(LOG_ERR, "could not map shared memory");
  598. exit(1);
  599. }
  600. SetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name);
  601. CopyMemory(shared_mem, &rate, sizeof(rate));
  602. // Get path to current exe
  603. char cmd_line[256 + MAX_PATH];
  604. const size_t n = sizeof(cmd_line)-200;
  605. DWORD size = GetModuleFileName(module, cmd_line, n);
  606. if (0==size) {
  607. applog(LOG_ERR, "failed to retrieve module path");
  608. exit(1);
  609. }
  610. // Construct new command line based on that
  611. char *p = strlen(cmd_line) + cmd_line;
  612. sprintf(p, " --bench-algo %d", algo);
  613. SetEnvironmentVariable("CGMINER_BENCH_ALGO", "1");
  614. // Launch a debug copy of cgminer
  615. STARTUPINFO startup_info;
  616. PROCESS_INFORMATION process_info;
  617. ZeroMemory(&startup_info, sizeof(startup_info));
  618. ZeroMemory(&process_info, sizeof(process_info));
  619. startup_info.cb = sizeof(startup_info);
  620. BOOL ok = CreateProcess(
  621. NULL, // No module name (use command line)
  622. cmd_line, // Command line
  623. NULL, // Process handle not inheritable
  624. NULL, // Thread handle not inheritable
  625. FALSE, // Set handle inheritance to FALSE
  626. DEBUG_ONLY_THIS_PROCESS,// We're going to debug the child
  627. NULL, // Use parent's environment block
  628. NULL, // Use parent's starting directory
  629. &startup_info, // Pointer to STARTUPINFO structure
  630. &process_info // Pointer to PROCESS_INFORMATION structure
  631. );
  632. if (!ok) {
  633. applog(LOG_ERR, "CreateProcess failed with error %d\n", GetLastError() );
  634. exit(1);
  635. }
  636. // Debug the child (only clean way to catch exceptions)
  637. while (1) {
  638. // Wait for child to do something
  639. DEBUG_EVENT debug_event;
  640. ZeroMemory(&debug_event, sizeof(debug_event));
  641. BOOL ok = WaitForDebugEvent(&debug_event, 60 * 1000);
  642. if (!ok)
  643. break;
  644. // Decide if event is "normal"
  645. int go_on =
  646. CREATE_PROCESS_DEBUG_EVENT== debug_event.dwDebugEventCode ||
  647. CREATE_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  648. EXIT_THREAD_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  649. EXCEPTION_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  650. LOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode ||
  651. OUTPUT_DEBUG_STRING_EVENT == debug_event.dwDebugEventCode ||
  652. UNLOAD_DLL_DEBUG_EVENT == debug_event.dwDebugEventCode;
  653. if (!go_on)
  654. break;
  655. // Some exceptions are also "normal", apparently.
  656. if (EXCEPTION_DEBUG_EVENT== debug_event.dwDebugEventCode) {
  657. int go_on =
  658. EXCEPTION_BREAKPOINT== debug_event.u.Exception.ExceptionRecord.ExceptionCode;
  659. if (!go_on)
  660. break;
  661. }
  662. // If nothing unexpected happened, let child proceed
  663. ContinueDebugEvent(
  664. debug_event.dwProcessId,
  665. debug_event.dwThreadId,
  666. DBG_CONTINUE
  667. );
  668. }
  669. // Clean up child process
  670. TerminateProcess(process_info.hProcess, 1);
  671. CloseHandle(process_info.hProcess);
  672. CloseHandle(process_info.hThread);
  673. // Reap return value and cleanup
  674. CopyMemory(&rate, shared_mem, sizeof(rate));
  675. (void)UnmapViewOfFile(shared_mem);
  676. (void)CloseHandle(map_handle);
  677. #else
  678. // Not linux, not unix, not WIN32 ... do our best
  679. rate = bench_algo_stage3(algo);
  680. #endif // defined(unix)
  681. // Done
  682. return rate;
  683. }
  684. static void bench_algo(
  685. double *best_rate,
  686. enum sha256_algos *best_algo,
  687. enum sha256_algos algo
  688. )
  689. {
  690. size_t n = max_name_len - strlen(algo_names[algo]);
  691. memset(name_spaces_pad, ' ', n);
  692. name_spaces_pad[n] = 0;
  693. applog(
  694. LOG_ERR,
  695. "\"%s\"%s : benchmarking algorithm ...",
  696. algo_names[algo],
  697. name_spaces_pad
  698. );
  699. double rate = bench_algo_stage2(algo);
  700. if (rate<0.0) {
  701. applog(
  702. LOG_ERR,
  703. "\"%s\"%s : algorithm fails on this platform",
  704. algo_names[algo],
  705. name_spaces_pad
  706. );
  707. } else {
  708. applog(
  709. LOG_ERR,
  710. "\"%s\"%s : algorithm runs at %.5f MH/s",
  711. algo_names[algo],
  712. name_spaces_pad,
  713. rate
  714. );
  715. if (*best_rate<rate) {
  716. *best_rate = rate;
  717. *best_algo = algo;
  718. }
  719. }
  720. }
  721. // Figure out the longest algorithm name
  722. static void init_max_name_len()
  723. {
  724. size_t i;
  725. size_t nb_names = sizeof(algo_names)/sizeof(algo_names[0]);
  726. for (i=0; i<nb_names; ++i) {
  727. const char *p = algo_names[i];
  728. size_t name_len = p ? strlen(p) : 0;
  729. if (max_name_len<name_len)
  730. max_name_len = name_len;
  731. }
  732. name_spaces_pad = (char*) malloc(max_name_len+16);
  733. if (0==name_spaces_pad) {
  734. perror("malloc failed");
  735. exit(1);
  736. }
  737. }
  738. // Pick the fastest CPU hasher
  739. static enum sha256_algos pick_fastest_algo()
  740. {
  741. double best_rate = -1.0;
  742. enum sha256_algos best_algo = 0;
  743. applog(LOG_ERR, "benchmarking all sha256 algorithms ...");
  744. bench_algo(&best_rate, &best_algo, ALGO_C);
  745. #if defined(WANT_SSE2_4WAY)
  746. bench_algo(&best_rate, &best_algo, ALGO_4WAY);
  747. #endif
  748. #if defined(WANT_VIA_PADLOCK)
  749. bench_algo(&best_rate, &best_algo, ALGO_VIA);
  750. #endif
  751. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP);
  752. #if defined(WANT_CRYPTOPP_ASM32)
  753. bench_algo(&best_rate, &best_algo, ALGO_CRYPTOPP_ASM32);
  754. #endif
  755. #if defined(WANT_X8632_SSE2)
  756. bench_algo(&best_rate, &best_algo, ALGO_SSE2_32);
  757. #endif
  758. #if defined(WANT_X8664_SSE2)
  759. bench_algo(&best_rate, &best_algo, ALGO_SSE2_64);
  760. #endif
  761. #if defined(WANT_X8664_SSE4)
  762. bench_algo(&best_rate, &best_algo, ALGO_SSE4_64);
  763. #endif
  764. size_t n = max_name_len - strlen(algo_names[best_algo]);
  765. memset(name_spaces_pad, ' ', n);
  766. name_spaces_pad[n] = 0;
  767. applog(
  768. LOG_ERR,
  769. "\"%s\"%s : is fastest algorithm at %.5f MH/s",
  770. algo_names[best_algo],
  771. name_spaces_pad,
  772. best_rate
  773. );
  774. return best_algo;
  775. }
  776. /* FIXME: Use asprintf for better errors. */
  777. static char *set_algo(const char *arg, enum sha256_algos *algo)
  778. {
  779. enum sha256_algos i;
  780. if (!strcmp(arg, "auto")) {
  781. *algo = pick_fastest_algo();
  782. return NULL;
  783. }
  784. for (i = 0; i < ARRAY_SIZE(algo_names); i++) {
  785. if (algo_names[i] && !strcmp(arg, algo_names[i])) {
  786. *algo = i;
  787. return NULL;
  788. }
  789. }
  790. return "Unknown algorithm";
  791. }
  792. static void show_algo(char buf[OPT_SHOW_LEN], const enum sha256_algos *algo)
  793. {
  794. strncpy(buf, algo_names[*algo], OPT_SHOW_LEN);
  795. }
  796. static char *set_int_range(const char *arg, int *i, int min, int max)
  797. {
  798. char *err = opt_set_intval(arg, i);
  799. if (err)
  800. return err;
  801. if (*i < min || *i > max)
  802. return "Value out of range";
  803. return NULL;
  804. }
  805. static char *set_int_0_to_9999(const char *arg, int *i)
  806. {
  807. return set_int_range(arg, i, 0, 9999);
  808. }
  809. static char *forced_int_1010(const char *arg, int *i)
  810. {
  811. opt_dynamic = false;
  812. return set_int_range(arg, i, -10, 10);
  813. }
  814. static char *force_nthreads_int(const char *arg, int *i)
  815. {
  816. forced_n_threads = true;
  817. return set_int_range(arg, i, 0, 9999);
  818. }
  819. static char *set_int_0_to_10(const char *arg, int *i)
  820. {
  821. return set_int_range(arg, i, 0, 10);
  822. }
  823. static char *set_int_1_to_10(const char *arg, int *i)
  824. {
  825. return set_int_range(arg, i, 1, 10);
  826. }
  827. static char *set_devices(const char *arg, int *i)
  828. {
  829. char *err = opt_set_intval(arg, i);
  830. if (err)
  831. return err;
  832. if (*i < 0 || *i > 15)
  833. return "Invalid GPU device number";
  834. total_devices++;
  835. gpu_devices[*i] = true;
  836. return NULL;
  837. }
  838. static char *set_loadbalance(enum pool_strategy *strategy)
  839. {
  840. *strategy = POOL_LOADBALANCE;
  841. return NULL;
  842. }
  843. static char *set_rotate(const char *arg, int *i)
  844. {
  845. pool_strategy = POOL_ROTATE;
  846. return set_int_range(arg, i, 0, 9999);
  847. }
  848. static char *set_rr(enum pool_strategy *strategy)
  849. {
  850. *strategy = POOL_ROUNDROBIN;
  851. return NULL;
  852. }
  853. static char *set_url(char *arg)
  854. {
  855. struct pool *pool;
  856. total_urls++;
  857. if (total_urls > total_pools)
  858. add_pool();
  859. pool = pools[total_urls - 1];
  860. opt_set_charp(arg, &pool->rpc_url);
  861. if (strncmp(arg, "http://", 7) &&
  862. strncmp(arg, "https://", 8)) {
  863. char *httpinput;
  864. httpinput = malloc(255);
  865. if (!httpinput)
  866. quit(1, "Failed to malloc httpinput");
  867. strcpy(httpinput, "http://");
  868. strncat(httpinput, arg, 248);
  869. pool->rpc_url = httpinput;
  870. }
  871. return NULL;
  872. }
  873. static char *set_user(const char *arg)
  874. {
  875. struct pool *pool;
  876. if (total_userpasses)
  877. return "Use only user + pass or userpass, but not both";
  878. total_users++;
  879. if (total_users > total_pools)
  880. add_pool();
  881. pool = pools[total_users - 1];
  882. opt_set_charp(arg, &pool->rpc_user);
  883. return NULL;
  884. }
  885. static char *set_pass(const char *arg)
  886. {
  887. struct pool *pool;
  888. if (total_userpasses)
  889. return "Use only user + pass or userpass, but not both";
  890. total_passes++;
  891. if (total_passes > total_pools)
  892. add_pool();
  893. pool = pools[total_passes - 1];
  894. opt_set_charp(arg, &pool->rpc_pass);
  895. return NULL;
  896. }
  897. static char *set_userpass(const char *arg)
  898. {
  899. struct pool *pool;
  900. if (total_users || total_passes)
  901. return "Use only user + pass or userpass, but not both";
  902. total_userpasses++;
  903. if (total_userpasses > total_pools)
  904. add_pool();
  905. pool = pools[total_userpasses - 1];
  906. opt_set_charp(arg, &pool->rpc_userpass);
  907. return NULL;
  908. }
  909. static char *set_vector(const char *arg, int *i)
  910. {
  911. char *err = opt_set_intval(arg, i);
  912. if (err)
  913. return err;
  914. if (*i != 1 && *i != 2 && *i != 4)
  915. return "Valid vectors are 1, 2 or 4";
  916. return NULL;
  917. }
  918. static char *enable_debug(bool *flag)
  919. {
  920. *flag = true;
  921. /* Turn out verbose output, too. */
  922. opt_log_output = true;
  923. return NULL;
  924. }
  925. static char *set_schedtime(const char *arg, struct schedtime *st)
  926. {
  927. if (sscanf(arg, "%d:%d", &st->tm.tm_hour, &st->tm.tm_min) != 2)
  928. return "Invalid time set, should be HH:MM";
  929. if (st->tm.tm_hour > 23 || st->tm.tm_min > 59 || st->tm.tm_hour < 0 || st->tm.tm_min < 0)
  930. return "Invalid time set.";
  931. st->enable = true;
  932. return NULL;
  933. }
  934. /* These options are available from config file or commandline */
  935. static struct opt_table opt_config_table[] = {
  936. OPT_WITH_ARG("--algo|-a",
  937. set_algo, show_algo, &opt_algo,
  938. "Specify sha256 implementation for CPU mining:\n"
  939. "\tauto\t\tBenchmark at startup and pick fastest algorithm"
  940. "\n\tc\t\tLinux kernel sha256, implemented in C"
  941. #ifdef WANT_SSE2_4WAY
  942. "\n\t4way\t\ttcatm's 4-way SSE2 implementation"
  943. #endif
  944. #ifdef WANT_VIA_PADLOCK
  945. "\n\tvia\t\tVIA padlock implementation"
  946. #endif
  947. "\n\tcryptopp\tCrypto++ C/C++ implementation"
  948. #ifdef WANT_CRYPTOPP_ASM32
  949. "\n\tcryptopp_asm32\tCrypto++ 32-bit assembler implementation"
  950. #endif
  951. #ifdef WANT_X8632_SSE2
  952. "\n\tsse2_32\t\tSSE2 32 bit implementation for i386 machines"
  953. #endif
  954. #ifdef WANT_X8664_SSE2
  955. "\n\tsse2_64\t\tSSE2 64 bit implementation for x86_64 machines"
  956. #endif
  957. #ifdef WANT_X8664_SSE4
  958. "\n\tsse4_64\t\tSSE4.1 64 bit implementation for x86_64 machines"
  959. #endif
  960. ),
  961. OPT_WITH_ARG("--bench-algo|-b",
  962. set_int_0_to_9999, opt_show_intval, &opt_bench_algo,
  963. opt_hidden),
  964. OPT_WITH_ARG("--cpu-threads|-t",
  965. force_nthreads_int, opt_show_intval, &opt_n_threads,
  966. "Number of miner CPU threads"),
  967. OPT_WITHOUT_ARG("--debug|-D",
  968. enable_debug, &opt_debug,
  969. "Enable debug output"),
  970. #ifdef HAVE_OPENCL
  971. OPT_WITH_ARG("--device|-d",
  972. set_devices, NULL, &opt_device,
  973. "Select device to use, (Use repeat -d for multiple devices, default: all)"),
  974. OPT_WITHOUT_ARG("--disable-gpu|-G",
  975. opt_set_bool, &opt_nogpu,
  976. "Disable GPU mining even if suitable devices exist"),
  977. OPT_WITHOUT_ARG("--enable-cpu|-C",
  978. opt_set_bool, &opt_usecpu,
  979. "Enable CPU mining with GPU mining (default: no CPU mining if suitable GPUs exist)"),
  980. OPT_WITHOUT_ARG("--failover-only",
  981. opt_set_bool, &opt_fail_only,
  982. "Don't leak work to backup pools when primary pool is lagging"),
  983. OPT_WITH_ARG("--gpu-threads|-g",
  984. set_int_1_to_10, opt_show_intval, &opt_g_threads,
  985. "Number of threads per GPU (1 - 10)"),
  986. OPT_WITH_ARG("--intensity|-I",
  987. forced_int_1010, NULL, &scan_intensity,
  988. "Intensity of GPU scanning (-10 -> 10, default: dynamic to maintain desktop interactivity)"),
  989. OPT_WITH_ARG("--kernel-path|-K",
  990. opt_set_charp, opt_show_charp, &opt_kernel_path,
  991. "Specify a path to where the kernel .cl files are"),
  992. OPT_WITH_ARG("--kernel|-k",
  993. opt_set_charp, NULL, &opt_kernel,
  994. "Select kernel to use (poclbm or phatk - default: auto)"),
  995. #endif
  996. OPT_WITHOUT_ARG("--load-balance",
  997. set_loadbalance, &pool_strategy,
  998. "Change multipool strategy from failover to even load balance"),
  999. OPT_WITH_ARG("--log|-l",
  1000. set_int_0_to_9999, opt_show_intval, &opt_log_interval,
  1001. "Interval in seconds between log output"),
  1002. #if defined(unix)
  1003. OPT_WITH_ARG("--monitor|-m",
  1004. opt_set_charp, NULL, &opt_stderr_cmd,
  1005. "Use custom pipe cmd for output messages"),
  1006. #endif // defined(unix)
  1007. OPT_WITHOUT_ARG("--no-longpoll",
  1008. opt_set_invbool, &want_longpoll,
  1009. "Disable X-Long-Polling support"),
  1010. #ifdef HAVE_OPENCL
  1011. OPT_WITHOUT_ARG("--no-restart",
  1012. opt_set_invbool, &opt_restart,
  1013. "Do not attempt to restart GPUs that hang"),
  1014. #endif
  1015. OPT_WITH_ARG("--pass|-p",
  1016. set_pass, NULL, NULL,
  1017. "Password for bitcoin JSON-RPC server"),
  1018. OPT_WITHOUT_ARG("--per-device-stats",
  1019. opt_set_bool, &want_per_device_stats,
  1020. "Force verbose mode and output per-device statistics"),
  1021. OPT_WITHOUT_ARG("--protocol-dump|-P",
  1022. opt_set_bool, &opt_protocol,
  1023. "Verbose dump of protocol-level activities"),
  1024. OPT_WITH_ARG("--queue|-Q",
  1025. set_int_0_to_10, opt_show_intval, &opt_queue,
  1026. "Minimum number of work items to have queued (0 - 10)"),
  1027. OPT_WITHOUT_ARG("--quiet|-q",
  1028. opt_set_bool, &opt_quiet,
  1029. "Disable logging output, display status and errors"),
  1030. OPT_WITHOUT_ARG("--real-quiet",
  1031. opt_set_bool, &opt_realquiet,
  1032. "Disable all output"),
  1033. OPT_WITH_ARG("--retries|-r",
  1034. opt_set_intval, opt_show_intval, &opt_retries,
  1035. "Number of times to retry before giving up, if JSON-RPC call fails (-1 means never)"),
  1036. OPT_WITH_ARG("--retry-pause|-R",
  1037. set_int_0_to_9999, opt_show_intval, &opt_fail_pause,
  1038. "Number of seconds to pause, between retries"),
  1039. OPT_WITH_ARG("--rotate",
  1040. set_rotate, opt_show_intval, &opt_rotate_period,
  1041. "Change multipool strategy from failover to regularly rotate at N minutes"),
  1042. OPT_WITHOUT_ARG("--round-robin",
  1043. set_rr, &pool_strategy,
  1044. "Change multipool strategy from failover to round robin on failure"),
  1045. OPT_WITH_ARG("--scan-time|-s",
  1046. set_int_0_to_9999, opt_show_intval, &opt_scantime,
  1047. "Upper bound on time spent scanning current work, in seconds"),
  1048. OPT_WITH_ARG("--sched-start",
  1049. set_schedtime, NULL, &schedstart,
  1050. "Set a time of day in HH:MM to start mining (a once off without a stop time)"),
  1051. OPT_WITH_ARG("--sched-stop",
  1052. set_schedtime, NULL, &schedstop,
  1053. "Set a time of day in HH:MM to stop mining (will quit without a start time)"),
  1054. OPT_WITH_ARG("--shares",
  1055. opt_set_intval, NULL, &opt_shares,
  1056. "Quit after mining N shares (default: unlimited)"),
  1057. OPT_WITHOUT_ARG("--submit-stale",
  1058. opt_set_bool, &opt_submit_stale,
  1059. "Submit shares even if they would normally be considered stale"),
  1060. #ifdef HAVE_SYSLOG_H
  1061. OPT_WITHOUT_ARG("--syslog",
  1062. opt_set_bool, &use_syslog,
  1063. "Use system log for output messages (default: standard error)"),
  1064. #endif
  1065. OPT_WITHOUT_ARG("--text-only|-T",
  1066. opt_set_invbool, &use_curses,
  1067. "Disable ncurses formatted screen output"),
  1068. OPT_WITH_ARG("--url|-o",
  1069. set_url, NULL, NULL,
  1070. "URL for bitcoin JSON-RPC server"),
  1071. OPT_WITH_ARG("--user|-u",
  1072. set_user, NULL, NULL,
  1073. "Username for bitcoin JSON-RPC server"),
  1074. #ifdef HAVE_OPENCL
  1075. OPT_WITH_ARG("--vectors|-v",
  1076. set_vector, NULL, &opt_vectors,
  1077. "Override detected optimal vector width (1, 2 or 4)"),
  1078. #endif
  1079. OPT_WITHOUT_ARG("--verbose",
  1080. opt_set_bool, &opt_log_output,
  1081. "Log verbose output to stderr as well as status output"),
  1082. #ifdef HAVE_OPENCL
  1083. OPT_WITH_ARG("--worksize|-w",
  1084. set_int_0_to_9999, opt_show_intval, &opt_worksize,
  1085. "Override detected optimal worksize"),
  1086. #endif
  1087. OPT_WITH_ARG("--userpass|-O",
  1088. set_userpass, NULL, NULL,
  1089. "Username:Password pair for bitcoin JSON-RPC server"),
  1090. OPT_ENDTABLE
  1091. };
  1092. static char *parse_config(json_t *config)
  1093. {
  1094. static char err_buf[200];
  1095. json_t *val;
  1096. struct opt_table *opt;
  1097. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1098. char *p, *name;
  1099. /* We don't handle subtables. */
  1100. assert(!(opt->type & OPT_SUBTABLE));
  1101. /* Pull apart the option name(s). */
  1102. name = strdup(opt->names);
  1103. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1104. char *err;
  1105. /* Ignore short options. */
  1106. if (p[1] != '-')
  1107. continue;
  1108. val = json_object_get(config, p+2);
  1109. if (!val)
  1110. continue;
  1111. if ((opt->type & OPT_HASARG) && json_is_string(val)) {
  1112. err = opt->cb_arg(json_string_value(val),
  1113. opt->u.arg);
  1114. } else if ((opt->type&OPT_NOARG) && json_is_true(val)) {
  1115. err = opt->cb(opt->u.arg);
  1116. } else {
  1117. err = "Invalid value";
  1118. }
  1119. if (err) {
  1120. sprintf(err_buf, "Parsing JSON option %s: %s",
  1121. p, err);
  1122. return err_buf;
  1123. }
  1124. }
  1125. free(name);
  1126. }
  1127. return NULL;
  1128. }
  1129. static char *load_config(const char *arg, void *unused)
  1130. {
  1131. json_error_t err;
  1132. json_t *config;
  1133. config = json_load_file(arg, 0, &err);
  1134. if (!json_is_object(config))
  1135. return "JSON decode of file failed";
  1136. /* Parse the config now, so we can override it. That can keep pointers
  1137. * so don't free config object. */
  1138. return parse_config(config);
  1139. }
  1140. #ifdef HAVE_OPENCL
  1141. static char *print_ndevs_and_exit(int *ndevs)
  1142. {
  1143. printf("%i GPU devices detected\n", *ndevs);
  1144. fflush(stdout);
  1145. exit(*ndevs);
  1146. }
  1147. #endif
  1148. extern const char *opt_argv0;
  1149. static char *opt_verusage_and_exit(const char *extra)
  1150. {
  1151. printf("%s\n"
  1152. #ifdef HAVE_OPENCL
  1153. "Built with CPU and GPU mining support.\n"
  1154. #else
  1155. "Built with CPU mining support only.\n"
  1156. #endif
  1157. , packagename);
  1158. printf("%s", opt_usage(opt_argv0, extra));
  1159. fflush(stdout);
  1160. exit(0);
  1161. }
  1162. /* These options are available from commandline only */
  1163. static struct opt_table opt_cmdline_table[] = {
  1164. OPT_WITH_ARG("--config|-c",
  1165. load_config, NULL, NULL,
  1166. "Load a JSON-format configuration file\n"
  1167. "See example-cfg.json for an example configuration."),
  1168. OPT_WITHOUT_ARG("--help|-h",
  1169. opt_verusage_and_exit, NULL,
  1170. "Print this message"),
  1171. #ifdef HAVE_OPENCL
  1172. OPT_WITHOUT_ARG("--ndevs|-n",
  1173. print_ndevs_and_exit, &nDevs,
  1174. "Enumerate number of detected GPUs and exit"),
  1175. #endif
  1176. OPT_WITHOUT_ARG("--version|-V",
  1177. opt_version_and_exit, packagename,
  1178. "Display version and exit"),
  1179. OPT_ENDTABLE
  1180. };
  1181. static bool jobj_binary(const json_t *obj, const char *key,
  1182. void *buf, size_t buflen)
  1183. {
  1184. const char *hexstr;
  1185. json_t *tmp;
  1186. tmp = json_object_get(obj, key);
  1187. if (unlikely(!tmp)) {
  1188. applog(LOG_ERR, "JSON key '%s' not found", key);
  1189. return false;
  1190. }
  1191. hexstr = json_string_value(tmp);
  1192. if (unlikely(!hexstr)) {
  1193. applog(LOG_ERR, "JSON key '%s' is not a string", key);
  1194. return false;
  1195. }
  1196. if (!hex2bin(buf, hexstr, buflen))
  1197. return false;
  1198. return true;
  1199. }
  1200. static bool work_decode(const json_t *val, struct work *work)
  1201. {
  1202. if (unlikely(!jobj_binary(val, "midstate",
  1203. work->midstate, sizeof(work->midstate)))) {
  1204. applog(LOG_ERR, "JSON inval midstate");
  1205. goto err_out;
  1206. }
  1207. if (unlikely(!jobj_binary(val, "data", work->data, sizeof(work->data)))) {
  1208. applog(LOG_ERR, "JSON inval data");
  1209. goto err_out;
  1210. }
  1211. if (unlikely(!jobj_binary(val, "hash1", work->hash1, sizeof(work->hash1)))) {
  1212. applog(LOG_ERR, "JSON inval hash1");
  1213. goto err_out;
  1214. }
  1215. if (unlikely(!jobj_binary(val, "target", work->target, sizeof(work->target)))) {
  1216. applog(LOG_ERR, "JSON inval target");
  1217. goto err_out;
  1218. }
  1219. memset(work->hash, 0, sizeof(work->hash));
  1220. gettimeofday(&work->tv_staged, NULL);
  1221. return true;
  1222. err_out:
  1223. return false;
  1224. }
  1225. static inline int dev_from_id(int thr_id)
  1226. {
  1227. return thr_info[thr_id].cgpu->cpu_gpu;
  1228. }
  1229. /* Make the change in the recent value adjust dynamically when the difference
  1230. * is large, but damp it when the values are closer together. This allows the
  1231. * value to change quickly, but not fluctuate too dramatically when it has
  1232. * stabilised. */
  1233. static void decay_time(double *f, double fadd)
  1234. {
  1235. double ratio = 0;
  1236. if (likely(*f > 0)) {
  1237. ratio = fadd / *f;
  1238. if (ratio > 1)
  1239. ratio = 1 / ratio;
  1240. }
  1241. if (ratio > 0.9)
  1242. *f = (fadd * 0.1 + *f) / 1.1;
  1243. else
  1244. *f = (fadd + *f * 0.1) / 1.1;
  1245. }
  1246. static int requests_staged(void)
  1247. {
  1248. int ret;
  1249. mutex_lock(&stgd_lock);
  1250. ret = HASH_COUNT(staged_work);
  1251. mutex_unlock(&stgd_lock);
  1252. return ret;
  1253. }
  1254. static WINDOW *mainwin, *statuswin, *logwin;
  1255. static double total_secs = 0.1;
  1256. static char statusline[256];
  1257. static int cpucursor, gpucursor, logstart, logcursor;
  1258. struct cgpu_info *gpus;
  1259. static struct cgpu_info *cpus;
  1260. static inline void unlock_curses(void)
  1261. {
  1262. mutex_unlock(&curses_lock);
  1263. }
  1264. static inline void lock_curses(void)
  1265. {
  1266. mutex_lock(&curses_lock);
  1267. }
  1268. static bool curses_active_locked(void)
  1269. {
  1270. bool ret;
  1271. lock_curses();
  1272. ret = curses_active;
  1273. if (!ret)
  1274. unlock_curses();
  1275. return ret;
  1276. }
  1277. static void text_print_status(int thr_id)
  1278. {
  1279. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1280. printf(" %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  1281. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  1282. cgpu->total_mhashes / total_secs, cgpu->getworks,
  1283. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1284. cgpu->efficiency, cgpu->utility);
  1285. }
  1286. /* Must be called with curses mutex lock held and curses_active */
  1287. static void curses_print_status(int thr_id)
  1288. {
  1289. struct pool *pool = current_pool();
  1290. wmove(statuswin, 0, 0);
  1291. wattron(statuswin, A_BOLD);
  1292. wprintw(statuswin, " " PACKAGE " version " VERSION " - Started: %s", datestamp);
  1293. if (opt_n_threads)
  1294. wprintw(statuswin, " CPU Algo: %s", algo_names[opt_algo]);
  1295. wattroff(statuswin, A_BOLD);
  1296. wmove(statuswin, 1, 0);
  1297. whline(statuswin, '-', 80);
  1298. wmove(statuswin, 2,0);
  1299. wprintw(statuswin, " %s", statusline);
  1300. wclrtoeol(statuswin);
  1301. wmove(statuswin, 3,0);
  1302. wprintw(statuswin, " TQ: %d ST: %d SS: %d DW: %d NB: %d LW: %d GF: %d RF: %d I: %d",
  1303. total_queued, requests_staged(), total_stale, total_discarded, new_blocks,
  1304. local_work, total_go, total_ro, scan_intensity);
  1305. wclrtoeol(statuswin);
  1306. wmove(statuswin, 4, 0);
  1307. if (pool_strategy == POOL_LOADBALANCE && total_pools > 1)
  1308. wprintw(statuswin, " Connected to multiple pools with%s LP",
  1309. have_longpoll ? "": "out");
  1310. else
  1311. wprintw(statuswin, " Connected to %s with%s LP as user %s",
  1312. pool->rpc_url, have_longpoll ? "": "out", pool->rpc_user);
  1313. wclrtoeol(statuswin);
  1314. wmove(statuswin, 5, 0);
  1315. wprintw(statuswin, " Block: %s... Started: %s", current_hash, blocktime);
  1316. wmove(statuswin, 6, 0);
  1317. whline(statuswin, '-', 80);
  1318. wmove(statuswin, logstart - 1, 0);
  1319. whline(statuswin, '-', 80);
  1320. mvwprintw(statuswin, gpucursor - 1, 1, "[P]ool management %s[S]ettings [D]isplay options [Q]uit",
  1321. opt_g_threads ? "[G]PU management " : "");
  1322. if (thr_id >= 0 && thr_id < gpu_threads) {
  1323. int gpu = dev_from_id(thr_id);
  1324. struct cgpu_info *cgpu = &gpus[gpu];
  1325. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1326. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1327. wmove(statuswin, gpucursor + gpu, 0);
  1328. wprintw(statuswin, " GPU %d: ", gpu);
  1329. if (cgpu->status == LIFE_DEAD)
  1330. wprintw(statuswin, "[DEAD ");
  1331. else if (cgpu->status == LIFE_SICK)
  1332. wprintw(statuswin, "[SICK ");
  1333. else if (!gpu_devices[gpu])
  1334. wprintw(statuswin, "[DISABLED ");
  1335. else
  1336. wprintw(statuswin, "[%.1f ", cgpu->rolling);
  1337. wprintw(statuswin, "/ %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  1338. cgpu->total_mhashes / total_secs,
  1339. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  1340. cgpu->efficiency, cgpu->utility);
  1341. wclrtoeol(statuswin);
  1342. } else if (thr_id >= gpu_threads) {
  1343. int cpu = dev_from_id(thr_id);
  1344. struct cgpu_info *cgpu = &cpus[cpu];
  1345. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1346. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1347. wmove(statuswin, cpucursor + cpu, 0);
  1348. wprintw(statuswin, " CPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d E:%.0f%% U:%.2f/m]",
  1349. cpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  1350. cgpu->getworks, cgpu->accepted, cgpu->rejected,
  1351. cgpu->efficiency, cgpu->utility);
  1352. wclrtoeol(statuswin);
  1353. }
  1354. wrefresh(statuswin);
  1355. }
  1356. static void print_status(int thr_id)
  1357. {
  1358. if (curses_active_locked()) {
  1359. curses_print_status(thr_id);
  1360. unlock_curses();
  1361. } else
  1362. text_print_status(thr_id);
  1363. }
  1364. /* Check for window resize. Called with curses mutex locked */
  1365. static inline bool change_logwinsize(void)
  1366. {
  1367. int x, y, logx, logy;
  1368. getmaxyx(mainwin, y, x);
  1369. getmaxyx(logwin, logy, logx);
  1370. y -= logcursor;
  1371. /* Detect screen size change */
  1372. if ((x != logx || y != logy) && x >= 80 && y >= 25) {
  1373. wresize(logwin, y, x);
  1374. return true;
  1375. }
  1376. return false;
  1377. }
  1378. /* For mandatory printing when mutex is already locked */
  1379. static void wlog(const char *f, ...)
  1380. {
  1381. va_list ap;
  1382. va_start(ap, f);
  1383. vw_printw(logwin, f, ap);
  1384. va_end(ap);
  1385. }
  1386. /* Mandatory printing */
  1387. void wlogprint(const char *f, ...)
  1388. {
  1389. va_list ap;
  1390. if (curses_active_locked()) {
  1391. va_start(ap, f);
  1392. vw_printw(logwin, f, ap);
  1393. va_end(ap);
  1394. wrefresh(logwin);
  1395. unlock_curses();
  1396. }
  1397. }
  1398. void log_curses(int prio, const char *f, va_list ap)
  1399. {
  1400. if (opt_quiet && prio != LOG_ERR)
  1401. return;
  1402. if (curses_active_locked()) {
  1403. if (!opt_loginput) {
  1404. vw_printw(logwin, f, ap);
  1405. wrefresh(logwin);
  1406. }
  1407. unlock_curses();
  1408. } else
  1409. vprintf(f, ap);
  1410. }
  1411. static void clear_logwin(void)
  1412. {
  1413. if (curses_active_locked()) {
  1414. wclear(logwin);
  1415. wrefresh(logwin);
  1416. unlock_curses();
  1417. }
  1418. }
  1419. static bool submit_upstream_work(const struct work *work)
  1420. {
  1421. char *hexstr = NULL;
  1422. json_t *val, *res;
  1423. char s[345], sd[345];
  1424. bool rc = false;
  1425. int thr_id = work->thr_id;
  1426. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  1427. CURL *curl = curl_easy_init();
  1428. struct pool *pool = work->pool;
  1429. bool rolltime;
  1430. if (unlikely(!curl)) {
  1431. applog(LOG_ERR, "CURL initialisation failed");
  1432. return rc;
  1433. }
  1434. /* build hex string */
  1435. hexstr = bin2hex(work->data, sizeof(work->data));
  1436. if (unlikely(!hexstr)) {
  1437. applog(LOG_ERR, "submit_upstream_work OOM");
  1438. goto out_nofree;
  1439. }
  1440. /* build JSON-RPC request */
  1441. sprintf(s,
  1442. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}\r\n",
  1443. hexstr);
  1444. sprintf(sd,
  1445. "{\"method\": \"getwork\", \"params\": [ \"%s\" ], \"id\":1}",
  1446. hexstr);
  1447. if (opt_debug)
  1448. applog(LOG_DEBUG, "DBG: sending %s submit RPC call: %s", pool->rpc_url, sd);
  1449. /* issue JSON-RPC request */
  1450. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, s, false, false, &rolltime, pool);
  1451. if (unlikely(!val)) {
  1452. applog(LOG_INFO, "submit_upstream_work json_rpc_call failed");
  1453. if (!pool_tset(pool, &pool->submit_fail)) {
  1454. total_ro++;
  1455. pool->remotefail_occasions++;
  1456. applog(LOG_WARNING, "Pool %d communication failure, caching submissions", pool->pool_no);
  1457. }
  1458. goto out;
  1459. } else if (pool_tclear(pool, &pool->submit_fail))
  1460. applog(LOG_WARNING, "Pool %d communication resumed, submitting work", pool->pool_no);
  1461. res = json_object_get(val, "result");
  1462. /* Theoretically threads could race when modifying accepted and
  1463. * rejected values but the chance of two submits completing at the
  1464. * same time is zero so there is no point adding extra locking */
  1465. if (json_is_true(res)) {
  1466. cgpu->accepted++;
  1467. total_accepted++;
  1468. pool->accepted++;
  1469. if (opt_debug)
  1470. applog(LOG_DEBUG, "PROOF OF WORK RESULT: true (yay!!!)");
  1471. if (!QUIET) {
  1472. if (total_pools > 1)
  1473. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d pool %d",
  1474. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1475. else
  1476. applog(LOG_WARNING, "Accepted %.8s %sPU %d thread %d",
  1477. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1478. }
  1479. if (opt_shares && total_accepted >= opt_shares) {
  1480. applog(LOG_WARNING, "Successfully mined %d accepted shares as requested and exiting.", opt_shares);
  1481. kill_work();
  1482. goto out;
  1483. }
  1484. } else {
  1485. cgpu->rejected++;
  1486. total_rejected++;
  1487. pool->rejected++;
  1488. if (opt_debug)
  1489. applog(LOG_DEBUG, "PROOF OF WORK RESULT: false (booooo)");
  1490. if (!QUIET) {
  1491. if (total_pools > 1)
  1492. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d pool %d",
  1493. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id, work->pool->pool_no);
  1494. else
  1495. applog(LOG_WARNING, "Rejected %.8s %sPU %d thread %d",
  1496. hexstr + 152, cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, thr_id);
  1497. }
  1498. }
  1499. cgpu->utility = cgpu->accepted / ( total_secs ? total_secs : 1 ) * 60;
  1500. cgpu->efficiency = cgpu->getworks ? cgpu->accepted * 100.0 / cgpu->getworks : 0.0;
  1501. if (!opt_realquiet)
  1502. print_status(thr_id);
  1503. if (!want_per_device_stats)
  1504. applog(LOG_INFO, "%sPU %d Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  1505. cgpu->is_gpu? "G" : "C", cgpu->cpu_gpu, cgpu->getworks, cgpu->accepted,
  1506. cgpu->rejected, cgpu->hw_errors, cgpu->efficiency, cgpu->utility);
  1507. json_decref(val);
  1508. rc = true;
  1509. out:
  1510. free(hexstr);
  1511. out_nofree:
  1512. curl_easy_cleanup(curl);
  1513. return rc;
  1514. }
  1515. static const char *rpc_req =
  1516. "{\"method\": \"getwork\", \"params\": [], \"id\":0}\r\n";
  1517. /* Select any active pool in a rotating fashion when loadbalance is chosen */
  1518. static inline struct pool *select_pool(bool lagging)
  1519. {
  1520. static int rotating_pool = 0;
  1521. struct pool *pool, *cp;
  1522. cp = current_pool();
  1523. if (pool_strategy != POOL_LOADBALANCE && !lagging)
  1524. pool = cp;
  1525. else
  1526. pool = NULL;
  1527. while (!pool) {
  1528. if (++rotating_pool >= total_pools)
  1529. rotating_pool = 0;
  1530. pool = pools[rotating_pool];
  1531. if ((!pool->idle && pool->enabled) || pool == cp)
  1532. break;
  1533. pool = NULL;
  1534. }
  1535. return pool;
  1536. }
  1537. static bool get_upstream_work(struct work *work, bool lagging)
  1538. {
  1539. struct pool *pool;
  1540. json_t *val;
  1541. bool rc = false;
  1542. CURL *curl;
  1543. curl = curl_easy_init();
  1544. if (unlikely(!curl)) {
  1545. applog(LOG_ERR, "CURL initialisation failed");
  1546. return rc;
  1547. }
  1548. pool = select_pool(lagging);
  1549. if (opt_debug)
  1550. applog(LOG_DEBUG, "DBG: sending %s get RPC call: %s", pool->rpc_url, rpc_req);
  1551. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  1552. false, false, &work->rolltime, pool);
  1553. if (unlikely(!val)) {
  1554. applog(LOG_DEBUG, "Failed json_rpc_call in get_upstream_work");
  1555. goto out;
  1556. }
  1557. rc = work_decode(json_object_get(val, "result"), work);
  1558. work->pool = pool;
  1559. total_getworks++;
  1560. pool->getwork_requested++;
  1561. if (work->thr)
  1562. work->thr->cgpu->getworks++;
  1563. json_decref(val);
  1564. out:
  1565. curl_easy_cleanup(curl);
  1566. return rc;
  1567. }
  1568. static struct work *make_work(void)
  1569. {
  1570. struct work *work = calloc(1, sizeof(struct work));
  1571. if (unlikely(!work))
  1572. quit(1, "Failed to calloc work in make_work");
  1573. work->id = total_work++;
  1574. return work;
  1575. }
  1576. static void free_work(struct work *work)
  1577. {
  1578. free(work);
  1579. }
  1580. static void workio_cmd_free(struct workio_cmd *wc)
  1581. {
  1582. if (!wc)
  1583. return;
  1584. switch (wc->cmd) {
  1585. case WC_SUBMIT_WORK:
  1586. free_work(wc->u.work);
  1587. break;
  1588. default: /* do nothing */
  1589. break;
  1590. }
  1591. memset(wc, 0, sizeof(*wc)); /* poison */
  1592. free(wc);
  1593. }
  1594. static void disable_curses(void)
  1595. {
  1596. if (curses_active_locked()) {
  1597. curses_active = false;
  1598. leaveok(logwin, false);
  1599. leaveok(statuswin, false);
  1600. leaveok(mainwin, false);
  1601. nocbreak();
  1602. echo();
  1603. delwin(logwin);
  1604. delwin(statuswin);
  1605. delwin(mainwin);
  1606. endwin();
  1607. refresh();
  1608. #ifdef WIN32
  1609. // Move the cursor to after curses output.
  1610. HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE);
  1611. CONSOLE_SCREEN_BUFFER_INFO csbi;
  1612. COORD coord;
  1613. if (GetConsoleScreenBufferInfo(hout, &csbi)) {
  1614. coord.X = 0;
  1615. coord.Y = csbi.dwSize.Y - 1;
  1616. SetConsoleCursorPosition(hout, coord);
  1617. }
  1618. #endif
  1619. unlock_curses();
  1620. }
  1621. }
  1622. static void print_summary(void);
  1623. void kill_work(void)
  1624. {
  1625. struct workio_cmd *wc;
  1626. struct thr_info *thr;
  1627. unsigned int i;
  1628. disable_curses();
  1629. applog(LOG_INFO, "Received kill message");
  1630. /* Kill the watchdog thread */
  1631. thr = &thr_info[watchdog_thr_id];
  1632. if (thr->pth)
  1633. pthread_cancel(*thr->pth);
  1634. /* Stop the mining threads*/
  1635. for (i = 0; i < mining_threads; i++) {
  1636. thr = &thr_info[i];
  1637. if (!thr->pth)
  1638. continue;
  1639. tq_freeze(thr->q);
  1640. /* No need to check if this succeeds or not */
  1641. pthread_cancel(*thr->pth);
  1642. }
  1643. /* Stop the others */
  1644. thr = &thr_info[stage_thr_id];
  1645. if (thr->pth)
  1646. pthread_cancel(*thr->pth);
  1647. thr = &thr_info[longpoll_thr_id];
  1648. if (thr->pth)
  1649. pthread_cancel(*thr->pth);
  1650. wc = calloc(1, sizeof(*wc));
  1651. if (unlikely(!wc)) {
  1652. applog(LOG_ERR, "Failed to calloc wc in kill_work");
  1653. /* We're just trying to die anyway, so forget graceful */
  1654. exit (1);
  1655. }
  1656. wc->cmd = WC_DIE;
  1657. wc->thr = 0;
  1658. if (opt_debug)
  1659. applog(LOG_DEBUG, "Pushing die request to work thread");
  1660. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  1661. applog(LOG_ERR, "Failed to tq_push work in kill_work");
  1662. exit (1);
  1663. }
  1664. thr = &thr_info[work_thr_id];
  1665. if (thr->pth)
  1666. pthread_cancel(*thr->pth);
  1667. }
  1668. void quit(int status, const char *format, ...);
  1669. static void sighandler(int sig)
  1670. {
  1671. /* Restore signal handlers so we can still quit if kill_work fails */
  1672. sigaction(SIGTERM, &termhandler, NULL);
  1673. sigaction(SIGINT, &inthandler, NULL);
  1674. kill_work();
  1675. quit(sig, "Received interrupt signal.");
  1676. }
  1677. static void *get_work_thread(void *userdata)
  1678. {
  1679. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1680. struct work *ret_work;
  1681. int failures = 0;
  1682. pthread_detach(pthread_self());
  1683. ret_work = make_work();
  1684. if (wc->thr)
  1685. ret_work->thr = wc->thr;
  1686. else
  1687. ret_work->thr = NULL;
  1688. /* obtain new work from bitcoin via JSON-RPC */
  1689. while (!get_upstream_work(ret_work, wc->lagging)) {
  1690. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1691. applog(LOG_ERR, "json_rpc_call failed, terminating workio thread");
  1692. free_work(ret_work);
  1693. kill_work();
  1694. goto out;
  1695. }
  1696. /* pause, then restart work-request loop */
  1697. applog(LOG_DEBUG, "json_rpc_call failed on get work, retry after %d seconds",
  1698. fail_pause);
  1699. sleep(fail_pause);
  1700. fail_pause += opt_fail_pause;
  1701. }
  1702. fail_pause = opt_fail_pause;
  1703. if (opt_debug)
  1704. applog(LOG_DEBUG, "Pushing work to requesting thread");
  1705. /* send work to requesting thread */
  1706. if (unlikely(!tq_push(thr_info[stage_thr_id].q, ret_work))) {
  1707. applog(LOG_ERR, "Failed to tq_push work in workio_get_work");
  1708. kill_work();
  1709. free_work(ret_work);
  1710. }
  1711. out:
  1712. workio_cmd_free(wc);
  1713. return NULL;
  1714. }
  1715. static bool workio_get_work(struct workio_cmd *wc)
  1716. {
  1717. pthread_t get_thread;
  1718. if (unlikely(pthread_create(&get_thread, NULL, get_work_thread, (void *)wc))) {
  1719. applog(LOG_ERR, "Failed to create get_work_thread");
  1720. return false;
  1721. }
  1722. return true;
  1723. }
  1724. static bool stale_work(struct work *work)
  1725. {
  1726. struct timeval now;
  1727. bool ret = false;
  1728. char *hexstr;
  1729. gettimeofday(&now, NULL);
  1730. if ((now.tv_sec - work->tv_staged.tv_sec) >= opt_scantime)
  1731. return true;
  1732. hexstr = bin2hex(work->data, 18);
  1733. if (unlikely(!hexstr)) {
  1734. applog(LOG_ERR, "submit_work_thread OOM");
  1735. return ret;
  1736. }
  1737. if (strcmp(hexstr, current_block))
  1738. ret = true;
  1739. free(hexstr);
  1740. return ret;
  1741. }
  1742. static void *submit_work_thread(void *userdata)
  1743. {
  1744. struct workio_cmd *wc = (struct workio_cmd *)userdata;
  1745. struct work *work = wc->u.work;
  1746. struct pool *pool = work->pool;
  1747. int failures = 0;
  1748. pthread_detach(pthread_self());
  1749. if (!opt_submit_stale && stale_work(work)) {
  1750. applog(LOG_WARNING, "Stale share detected, discarding");
  1751. total_stale++;
  1752. pool->stale_shares++;
  1753. goto out;
  1754. }
  1755. /* submit solution to bitcoin via JSON-RPC */
  1756. while (!submit_upstream_work(work)) {
  1757. if (!opt_submit_stale && stale_work(work)) {
  1758. applog(LOG_WARNING, "Stale share detected, discarding");
  1759. total_stale++;
  1760. pool->stale_shares++;
  1761. break;
  1762. }
  1763. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1764. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1765. kill_work();
  1766. break;
  1767. }
  1768. /* pause, then restart work-request loop */
  1769. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1770. fail_pause);
  1771. sleep(fail_pause);
  1772. fail_pause += opt_fail_pause;
  1773. }
  1774. fail_pause = opt_fail_pause;
  1775. out:
  1776. workio_cmd_free(wc);
  1777. return NULL;
  1778. }
  1779. static bool workio_submit_work(struct workio_cmd *wc)
  1780. {
  1781. pthread_t submit_thread;
  1782. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1783. applog(LOG_ERR, "Failed to create submit_work_thread");
  1784. return false;
  1785. }
  1786. return true;
  1787. }
  1788. /* Find the pool that currently has the highest priority */
  1789. static struct pool *priority_pool(int choice)
  1790. {
  1791. struct pool *ret = NULL;
  1792. int i;
  1793. for (i = 0; i < total_pools; i++) {
  1794. struct pool *pool = pools[i];
  1795. if (pool->prio == choice) {
  1796. ret = pool;
  1797. break;
  1798. }
  1799. }
  1800. if (unlikely(!ret)) {
  1801. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1802. return pools[choice];
  1803. }
  1804. return ret;
  1805. }
  1806. static void restart_longpoll(void);
  1807. static void switch_pools(struct pool *selected)
  1808. {
  1809. struct pool *pool, *last_pool;
  1810. int i, pool_no;
  1811. mutex_lock(&control_lock);
  1812. last_pool = currentpool;
  1813. pool_no = currentpool->pool_no;
  1814. /* Switch selected to pool number 0 and move the rest down */
  1815. if (selected) {
  1816. if (selected->prio != 0) {
  1817. for (i = 0; i < total_pools; i++) {
  1818. pool = pools[i];
  1819. if (pool->prio < selected->prio)
  1820. pool->prio++;
  1821. }
  1822. selected->prio = 0;
  1823. }
  1824. }
  1825. switch (pool_strategy) {
  1826. /* Both of these set to the master pool */
  1827. case POOL_FAILOVER:
  1828. case POOL_LOADBALANCE:
  1829. for (i = 0; i < total_pools; i++) {
  1830. pool = priority_pool(i);
  1831. if (!pool->idle && pool->enabled) {
  1832. pool_no = pool->pool_no;
  1833. break;
  1834. }
  1835. }
  1836. break;
  1837. /* Both of these simply increment and cycle */
  1838. case POOL_ROUNDROBIN:
  1839. case POOL_ROTATE:
  1840. if (selected) {
  1841. pool_no = selected->pool_no;
  1842. break;
  1843. }
  1844. pool_no++;
  1845. if (pool_no >= total_pools)
  1846. pool_no = 0;
  1847. break;
  1848. default:
  1849. break;
  1850. }
  1851. currentpool = pools[pool_no];
  1852. pool = currentpool;
  1853. mutex_unlock(&control_lock);
  1854. if (pool != last_pool) {
  1855. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1856. /* Only switch longpoll if the new pool also supports LP */
  1857. if (pool->hdr_path)
  1858. restart_longpoll();
  1859. }
  1860. /* Reset the queued amount to allow more to be queued for the new pool */
  1861. mutex_lock(&qd_lock);
  1862. total_queued = 0;
  1863. mutex_unlock(&qd_lock);
  1864. }
  1865. static void discard_work(struct work *work)
  1866. {
  1867. if (!work->clone && !work->rolls && !work->mined) {
  1868. if (work->pool)
  1869. work->pool->discarded_work++;
  1870. total_discarded++;
  1871. if (opt_debug)
  1872. applog(LOG_DEBUG, "Discarded work");
  1873. } else if (opt_debug)
  1874. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  1875. free_work(work);
  1876. }
  1877. /* This is overkill, but at least we'll know accurately how much work is
  1878. * queued to prevent ever being left without work */
  1879. static void inc_queued(void)
  1880. {
  1881. mutex_lock(&qd_lock);
  1882. total_queued++;
  1883. mutex_unlock(&qd_lock);
  1884. }
  1885. static void dec_queued(void)
  1886. {
  1887. mutex_lock(&qd_lock);
  1888. if (total_queued > 0)
  1889. total_queued--;
  1890. mutex_unlock(&qd_lock);
  1891. }
  1892. static int requests_queued(void)
  1893. {
  1894. int ret;
  1895. mutex_lock(&qd_lock);
  1896. ret = total_queued;
  1897. mutex_unlock(&qd_lock);
  1898. return ret;
  1899. }
  1900. static int discard_stale(void)
  1901. {
  1902. struct work *work, *tmp;
  1903. int i, stale = 0;
  1904. mutex_lock(&stgd_lock);
  1905. HASH_ITER(hh, staged_work, work, tmp) {
  1906. if (stale_work(work)) {
  1907. HASH_DEL(staged_work, work);
  1908. discard_work(work);
  1909. stale++;
  1910. }
  1911. }
  1912. mutex_unlock(&stgd_lock);
  1913. if (opt_debug)
  1914. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  1915. /* Dec queued outside the loop to not have recursive locks */
  1916. for (i = 0; i < stale; i++)
  1917. dec_queued();
  1918. return stale;
  1919. }
  1920. static bool queue_request(struct thr_info *thr, bool needed);
  1921. static void restart_threads(void)
  1922. {
  1923. int i, stale;
  1924. /* Discard staged work that is now stale */
  1925. stale = discard_stale();
  1926. for (i = 0; i < stale; i++)
  1927. queue_request(NULL, true);
  1928. for (i = 0; i < mining_threads; i++)
  1929. work_restart[i].restart = 1;
  1930. }
  1931. static void set_curblock(char *hexstr, unsigned char *hash)
  1932. {
  1933. unsigned char hash_swap[32];
  1934. char *old_hash = NULL;
  1935. struct timeval tv_now;
  1936. /* Don't free current_hash directly to avoid dereferencing it when
  1937. * we might be accessing its data elsewhere */
  1938. if (current_hash)
  1939. old_hash = current_hash;
  1940. strcpy(current_block, hexstr);
  1941. gettimeofday(&tv_now, NULL);
  1942. get_timestamp(blocktime, &tv_now);
  1943. swap256(hash_swap, hash);
  1944. current_hash = bin2hex(hash_swap, 16);
  1945. if (unlikely(!current_hash))
  1946. quit (1, "set_curblock OOM");
  1947. if (old_hash)
  1948. free(old_hash);
  1949. }
  1950. static void test_work_current(struct work *work)
  1951. {
  1952. struct block *s;
  1953. char *hexstr;
  1954. hexstr = bin2hex(work->data, 18);
  1955. if (unlikely(!hexstr)) {
  1956. applog(LOG_ERR, "stage_thread OOM");
  1957. return;
  1958. }
  1959. /* Search to see if this block exists yet and if not, consider it a
  1960. * new block and set the current block details to this one */
  1961. rd_lock(&blk_lock);
  1962. HASH_FIND_STR(blocks, hexstr, s);
  1963. rd_unlock(&blk_lock);
  1964. if (!s) {
  1965. s = calloc(sizeof(struct block), 1);
  1966. if (unlikely(!s))
  1967. quit (1, "test_work_current OOM");
  1968. strcpy(s->hash, hexstr);
  1969. wr_lock(&blk_lock);
  1970. HASH_ADD_STR(blocks, hash, s);
  1971. wr_unlock(&blk_lock);
  1972. set_curblock(hexstr, work->data);
  1973. new_blocks++;
  1974. if (block_changed != BLOCK_LP && block_changed != BLOCK_FIRST) {
  1975. block_changed = BLOCK_DETECT;
  1976. if (have_longpoll)
  1977. applog(LOG_WARNING, "New block detected on network before longpoll, waiting on fresh work");
  1978. else
  1979. applog(LOG_WARNING, "New block detected on network, waiting on fresh work");
  1980. } else
  1981. block_changed = BLOCK_NONE;
  1982. restart_threads();
  1983. }
  1984. free(hexstr);
  1985. }
  1986. static int tv_sort(struct work *worka, struct work *workb)
  1987. {
  1988. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  1989. }
  1990. static bool hash_push(struct work *work)
  1991. {
  1992. bool rc = true;
  1993. mutex_lock(&getq->mutex);
  1994. if (likely(!getq->frozen)) {
  1995. HASH_ADD_INT(staged_work, id, work);
  1996. HASH_SORT(staged_work, tv_sort);
  1997. } else
  1998. rc = false;
  1999. pthread_cond_signal(&getq->cond);
  2000. mutex_unlock(&getq->mutex);
  2001. return rc;
  2002. }
  2003. static void *stage_thread(void *userdata)
  2004. {
  2005. struct thr_info *mythr = userdata;
  2006. bool ok = true;
  2007. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2008. while (ok) {
  2009. struct work *work = NULL;
  2010. if (opt_debug)
  2011. applog(LOG_DEBUG, "Popping work to stage thread");
  2012. work = tq_pop(mythr->q, NULL);
  2013. if (unlikely(!work)) {
  2014. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  2015. ok = false;
  2016. break;
  2017. }
  2018. test_work_current(work);
  2019. if (opt_debug)
  2020. applog(LOG_DEBUG, "Pushing work to getwork queue");
  2021. if (unlikely(!hash_push(work))) {
  2022. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  2023. continue;
  2024. }
  2025. }
  2026. tq_freeze(mythr->q);
  2027. return NULL;
  2028. }
  2029. int curses_int(const char *query)
  2030. {
  2031. int ret;
  2032. char *cvar;
  2033. cvar = curses_input(query);
  2034. ret = atoi(cvar);
  2035. free(cvar);
  2036. return ret;
  2037. }
  2038. static bool input_pool(bool live);
  2039. static int active_pools(void)
  2040. {
  2041. int ret = 0;
  2042. int i;
  2043. for (i = 0; i < total_pools; i++) {
  2044. if ((pools[i])->enabled)
  2045. ret++;
  2046. }
  2047. return ret;
  2048. }
  2049. static void display_pool_summary(struct pool *pool)
  2050. {
  2051. double efficiency = 0.0;
  2052. if (curses_active_locked()) {
  2053. wlog("Pool: %s\n", pool->rpc_url);
  2054. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  2055. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  2056. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  2057. wlog(" Accepted shares: %d\n", pool->accepted);
  2058. wlog(" Rejected shares: %d\n", pool->rejected);
  2059. if (pool->accepted || pool->rejected)
  2060. wlog(" Reject ratio: %.1f\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  2061. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  2062. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  2063. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  2064. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  2065. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  2066. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  2067. wrefresh(logwin);
  2068. unlock_curses();
  2069. }
  2070. }
  2071. /* We can't remove the memory used for this struct pool because there may
  2072. * still be work referencing it. We just remove it from the pools list */
  2073. static void remove_pool(struct pool *pool)
  2074. {
  2075. int i, last_pool = total_pools - 1;
  2076. struct pool *other;
  2077. /* Boost priority of any lower prio than this one */
  2078. for (i = 0; i < total_pools; i++) {
  2079. other = pools[i];
  2080. if (other->prio > pool->prio)
  2081. other->prio--;
  2082. }
  2083. if (pool->pool_no < last_pool) {
  2084. /* Swap the last pool for this one */
  2085. (pools[last_pool])->pool_no = pool->pool_no;
  2086. pools[pool->pool_no] = pools[last_pool];
  2087. }
  2088. /* Give it an invalid number */
  2089. pool->pool_no = total_pools;
  2090. total_pools--;
  2091. }
  2092. static void display_pools(void)
  2093. {
  2094. struct pool *pool;
  2095. int selected, i;
  2096. char input;
  2097. opt_loginput = true;
  2098. immedok(logwin, true);
  2099. updated:
  2100. clear_logwin();
  2101. for (i = 0; i < total_pools; i++) {
  2102. pool = pools[i];
  2103. if (pool == current_pool())
  2104. wattron(logwin, A_BOLD);
  2105. if (!pool->enabled)
  2106. wattron(logwin, A_DIM);
  2107. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2108. pool->pool_no,
  2109. pool->enabled? "Enabled" : "Disabled",
  2110. pool->idle? "Dead" : "Alive",
  2111. pool->prio,
  2112. pool->rpc_url, pool->rpc_user);
  2113. wattroff(logwin, A_BOLD | A_DIM);
  2114. }
  2115. retry:
  2116. wlogprint("\nCurrent pool management strategy: %s\n",
  2117. strategies[pool_strategy]);
  2118. if (pool_strategy == POOL_ROTATE)
  2119. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2120. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2121. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2122. wlogprint("Or press any other key to continue\n");
  2123. input = getch();
  2124. if (!strncasecmp(&input, "a", 1)) {
  2125. input_pool(true);
  2126. goto updated;
  2127. } else if (!strncasecmp(&input, "r", 1)) {
  2128. if (total_pools <= 1) {
  2129. wlogprint("Cannot remove last pool");
  2130. goto retry;
  2131. }
  2132. selected = curses_int("Select pool number");
  2133. if (selected < 0 || selected >= total_pools) {
  2134. wlogprint("Invalid selection\n");
  2135. goto retry;
  2136. }
  2137. pool = pools[selected];
  2138. if (pool == current_pool())
  2139. switch_pools(NULL);
  2140. if (pool == current_pool()) {
  2141. wlogprint("Unable to remove pool due to activity\n");
  2142. goto retry;
  2143. }
  2144. pool->enabled = false;
  2145. remove_pool(pool);
  2146. goto updated;
  2147. } else if (!strncasecmp(&input, "s", 1)) {
  2148. selected = curses_int("Select pool number");
  2149. if (selected < 0 || selected >= total_pools) {
  2150. wlogprint("Invalid selection\n");
  2151. goto retry;
  2152. }
  2153. pool = pools[selected];
  2154. pool->enabled = true;
  2155. switch_pools(pool);
  2156. goto updated;
  2157. } else if (!strncasecmp(&input, "d", 1)) {
  2158. if (active_pools() <= 1) {
  2159. wlogprint("Cannot disable last pool");
  2160. goto retry;
  2161. }
  2162. selected = curses_int("Select pool number");
  2163. if (selected < 0 || selected >= total_pools) {
  2164. wlogprint("Invalid selection\n");
  2165. goto retry;
  2166. }
  2167. pool = pools[selected];
  2168. pool->enabled = false;
  2169. if (pool == current_pool())
  2170. switch_pools(NULL);
  2171. goto updated;
  2172. } else if (!strncasecmp(&input, "e", 1)) {
  2173. selected = curses_int("Select pool number");
  2174. if (selected < 0 || selected >= total_pools) {
  2175. wlogprint("Invalid selection\n");
  2176. goto retry;
  2177. }
  2178. pool = pools[selected];
  2179. pool->enabled = true;
  2180. if (pool->prio < current_pool()->prio)
  2181. switch_pools(pool);
  2182. goto updated;
  2183. } else if (!strncasecmp(&input, "c", 1)) {
  2184. for (i = 0; i <= TOP_STRATEGY; i++)
  2185. wlogprint("%d: %s\n", i, strategies[i]);
  2186. selected = curses_int("Select strategy number type");
  2187. if (selected < 0 || selected > TOP_STRATEGY) {
  2188. wlogprint("Invalid selection\n");
  2189. goto retry;
  2190. }
  2191. if (selected == POOL_ROTATE) {
  2192. opt_rotate_period = curses_int("Select interval in minutes");
  2193. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2194. opt_rotate_period = 0;
  2195. wlogprint("Invalid selection\n");
  2196. goto retry;
  2197. }
  2198. }
  2199. pool_strategy = selected;
  2200. switch_pools(NULL);
  2201. goto updated;
  2202. } else if (!strncasecmp(&input, "i", 1)) {
  2203. selected = curses_int("Select pool number");
  2204. if (selected < 0 || selected >= total_pools) {
  2205. wlogprint("Invalid selection\n");
  2206. goto retry;
  2207. }
  2208. pool = pools[selected];
  2209. display_pool_summary(pool);
  2210. goto retry;
  2211. }
  2212. clear_logwin();
  2213. immedok(logwin, false);
  2214. opt_loginput = false;
  2215. }
  2216. static void display_options(void)
  2217. {
  2218. int selected;
  2219. char input;
  2220. opt_loginput = true;
  2221. immedok(logwin, true);
  2222. retry:
  2223. clear_logwin();
  2224. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2225. wlogprint("[D]ebug:%s\n[P]er-device:%s\n[Q]uiet:%s\n[V]erbose:%s\n[R]PC debug:%s\n[L]og interval:%d\n",
  2226. opt_debug ? "on" : "off",
  2227. want_per_device_stats? "on" : "off",
  2228. opt_quiet ? "on" : "off",
  2229. opt_log_output ? "on" : "off",
  2230. opt_protocol ? "on" : "off",
  2231. opt_log_interval);
  2232. wlogprint("Select an option or any other key to return\n");
  2233. input = getch();
  2234. if (!strncasecmp(&input, "q", 1)) {
  2235. opt_quiet ^= true;
  2236. clear_logwin();
  2237. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2238. } else if (!strncasecmp(&input, "v", 1)) {
  2239. opt_log_output ^= true;
  2240. if (opt_log_output)
  2241. opt_quiet = false;
  2242. clear_logwin();
  2243. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2244. } else if (!strncasecmp(&input, "n", 1)) {
  2245. opt_log_output = false;
  2246. opt_debug = false;
  2247. opt_quiet = false;
  2248. opt_protocol = false;
  2249. want_per_device_stats = false;
  2250. clear_logwin();
  2251. wlogprint("Output mode reset to normal\n");
  2252. } else if (!strncasecmp(&input, "d", 1)) {
  2253. opt_debug ^= true;
  2254. opt_log_output = opt_debug;
  2255. if (opt_debug)
  2256. opt_quiet = false;
  2257. clear_logwin();
  2258. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2259. } else if (!strncasecmp(&input, "p", 1)) {
  2260. want_per_device_stats ^= true;
  2261. opt_log_output = want_per_device_stats;
  2262. clear_logwin();
  2263. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2264. } else if (!strncasecmp(&input, "r", 1)) {
  2265. opt_protocol ^= true;
  2266. if (opt_protocol)
  2267. opt_quiet = false;
  2268. clear_logwin();
  2269. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2270. } else if (!strncasecmp(&input, "c", 1))
  2271. clear_logwin();
  2272. else if (!strncasecmp(&input, "l", 1)) {
  2273. selected = curses_int("Interval in seconds");
  2274. if (selected < 0 || selected > 9999) {
  2275. wlogprint("Invalid selection\n");
  2276. goto retry;
  2277. }
  2278. opt_log_interval = selected;
  2279. clear_logwin();
  2280. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2281. } else if (!strncasecmp(&input, "s", 1)) {
  2282. opt_realquiet = true;
  2283. clear_logwin();
  2284. } else clear_logwin();
  2285. immedok(logwin, false);
  2286. opt_loginput = false;
  2287. }
  2288. static void set_options(void)
  2289. {
  2290. int selected;
  2291. char input;
  2292. opt_loginput = true;
  2293. immedok(logwin, true);
  2294. retry:
  2295. clear_logwin();
  2296. wlogprint("\n[D]ynamic mode: %s\n[L]ongpoll: %s\n",
  2297. opt_dynamic ? "On" : "Off", want_longpoll ? "On" : "Off");
  2298. if (opt_dynamic)
  2299. wlogprint("[I]ntensity: Dynamic\n");
  2300. else
  2301. wlogprint("[I]ntensity: %d\n", scan_intensity);
  2302. wlogprint("[Q]ueue: %d\n[S]cantime: %d\n[R]etries: %d\n[P]ause: %d\n",
  2303. opt_queue, opt_scantime, opt_retries, opt_fail_pause);
  2304. wlogprint("Select an option or any other key to return\n");
  2305. input = getch();
  2306. if (!strncasecmp(&input, "q", 1)) {
  2307. selected = curses_int("Extra work items to queue");
  2308. if (selected < 0 || selected > 9999) {
  2309. wlogprint("Invalid selection\n");
  2310. goto retry;
  2311. }
  2312. opt_queue = selected;
  2313. goto retry;
  2314. } else if (!strncasecmp(&input, "d", 1)) {
  2315. opt_dynamic ^= true;
  2316. goto retry;
  2317. } else if (!strncasecmp(&input, "l", 1)) {
  2318. want_longpoll ^= true;
  2319. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2320. restart_longpoll();
  2321. goto retry;
  2322. } else if (!strncasecmp(&input, "i", 1)) {
  2323. selected = curses_int("Set GPU scan intensity (-10 -> 10)");
  2324. if (selected < -10 || selected > 10) {
  2325. wlogprint("Invalid selection\n");
  2326. goto retry;
  2327. }
  2328. opt_dynamic = false;
  2329. scan_intensity = selected;
  2330. goto retry;
  2331. } else if (!strncasecmp(&input, "s", 1)) {
  2332. selected = curses_int("Set scantime in seconds");
  2333. if (selected < 0 || selected > 9999) {
  2334. wlogprint("Invalid selection\n");
  2335. goto retry;
  2336. }
  2337. opt_scantime = selected;
  2338. goto retry;
  2339. } else if (!strncasecmp(&input, "r", 1)) {
  2340. selected = curses_int("Retries before failing (-1 infinite)");
  2341. if (selected < -1 || selected > 9999) {
  2342. wlogprint("Invalid selection\n");
  2343. goto retry;
  2344. }
  2345. opt_retries = selected;
  2346. goto retry;
  2347. } else if (!strncasecmp(&input, "p", 1)) {
  2348. selected = curses_int("Seconds to pause before network retries");
  2349. if (selected < 1 || selected > 9999) {
  2350. wlogprint("Invalid selection\n");
  2351. goto retry;
  2352. }
  2353. opt_fail_pause = selected;
  2354. goto retry;
  2355. }
  2356. clear_logwin();
  2357. immedok(logwin, false);
  2358. opt_loginput = false;
  2359. }
  2360. #ifdef HAVE_OPENCL
  2361. static void reinit_device(struct cgpu_info *cgpu);
  2362. static void manage_gpu(void)
  2363. {
  2364. struct thr_info *thr;
  2365. int selected, gpu, i;
  2366. char checkin[40];
  2367. char input;
  2368. if (!opt_g_threads)
  2369. return;
  2370. opt_loginput = true;
  2371. immedok(logwin, true);
  2372. clear_logwin();
  2373. retry:
  2374. for (gpu = 0; gpu < nDevs; gpu++) {
  2375. struct cgpu_info *cgpu = &gpus[gpu];
  2376. wlog("GPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]\n",
  2377. gpu, cgpu->rolling, cgpu->total_mhashes / total_secs,
  2378. cgpu->getworks, cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  2379. cgpu->efficiency, cgpu->utility);
  2380. #ifdef HAVE_ADL
  2381. if (gpus[gpu].has_adl)
  2382. wlog("Temp: %.1f °C\nFan Speed: %d RPM\nEngine Clock: %d MHz\nMemory Clock: %d Mhz\nVddc: %.3f V\nActivity: %d%%\n",
  2383. gpu_temp(gpu), gpu_fanspeed(gpu), gpu_engineclock(gpu), gpu_memclock(gpu), gpu_vddc(gpu), gpu_activity(gpu));
  2384. #endif
  2385. wlog("Last initialised: %s\n", cgpu->init);
  2386. for (i = 0; i < mining_threads; i++) {
  2387. thr = &thr_info[i];
  2388. if (thr->cgpu != cgpu)
  2389. continue;
  2390. get_datestamp(checkin, &thr->last);
  2391. wlog("Thread %d: %.1f Mh/s %s ", i, thr->rolling, gpu_devices[gpu] ? "Enabled" : "Disabled");
  2392. switch (cgpu->status) {
  2393. default:
  2394. case LIFE_WELL:
  2395. wlog("ALIVE");
  2396. break;
  2397. case LIFE_SICK:
  2398. wlog("SICK reported in %s", checkin);
  2399. break;
  2400. case LIFE_DEAD:
  2401. wlog("DEAD reported in %s", checkin);
  2402. break;
  2403. }
  2404. wlog("\n");
  2405. }
  2406. wlog("\n");
  2407. }
  2408. wlogprint("[E]nable [D]isable [R]estart GPU %s\n",adl_active ? "[C]hange settings" : "");
  2409. wlogprint("Or press any other key to continue\n");
  2410. input = getch();
  2411. if (!strncasecmp(&input, "e", 1)) {
  2412. selected = curses_int("Select GPU to enable");
  2413. if (selected < 0 || selected >= nDevs) {
  2414. wlogprint("Invalid selection\n");
  2415. goto retry;
  2416. }
  2417. if (gpu_devices[selected]) {
  2418. wlogprint("Device already enabled\n");
  2419. goto retry;
  2420. }
  2421. gpu_devices[selected] = true;
  2422. for (i = 0; i < gpu_threads; i++) {
  2423. if (dev_from_id(i) != selected)
  2424. continue;
  2425. thr = &thr_info[i];
  2426. if (opt_debug)
  2427. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  2428. tq_push(thr->q, &ping);
  2429. }
  2430. } if (!strncasecmp(&input, "d", 1)) {
  2431. selected = curses_int("Select GPU to disable");
  2432. if (selected < 0 || selected >= nDevs) {
  2433. wlogprint("Invalid selection\n");
  2434. goto retry;
  2435. }
  2436. if (!gpu_devices[selected]) {
  2437. wlogprint("Device already disabled\n");
  2438. goto retry;
  2439. }
  2440. gpu_devices[selected] = false;
  2441. } else if (!strncasecmp(&input, "r", 1)) {
  2442. selected = curses_int("Select GPU to attempt to restart");
  2443. if (selected < 0 || selected >= nDevs) {
  2444. wlogprint("Invalid selection\n");
  2445. goto retry;
  2446. }
  2447. wlogprint("Attempting to restart threads of GPU %d\n", selected);
  2448. reinit_device(&gpus[selected]);
  2449. } else if (adl_active && (!strncasecmp(&input, "c", 1))) {
  2450. selected = curses_int("Select GPU to change settings on");
  2451. if (selected < 0 || selected >= nDevs) {
  2452. wlogprint("Invalid selection\n");
  2453. goto retry;
  2454. }
  2455. change_gpusettings(selected);
  2456. }
  2457. clear_logwin();
  2458. immedok(logwin, false);
  2459. opt_loginput = false;
  2460. }
  2461. #else
  2462. static void manage_gpu(void)
  2463. {
  2464. }
  2465. #endif
  2466. static void *input_thread(void *userdata)
  2467. {
  2468. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2469. if (!curses_active)
  2470. return NULL;
  2471. while (1) {
  2472. char input;
  2473. input = getch();
  2474. if (!strncasecmp(&input, "q", 1)) {
  2475. kill_work();
  2476. return NULL;
  2477. } else if (!strncasecmp(&input, "d", 1))
  2478. display_options();
  2479. else if (!strncasecmp(&input, "p", 1))
  2480. display_pools();
  2481. else if (!strncasecmp(&input, "s", 1))
  2482. set_options();
  2483. else if (!strncasecmp(&input, "g", 1))
  2484. manage_gpu();
  2485. if (opt_realquiet) {
  2486. disable_curses();
  2487. break;
  2488. }
  2489. }
  2490. return NULL;
  2491. }
  2492. static void *workio_thread(void *userdata)
  2493. {
  2494. struct thr_info *mythr = userdata;
  2495. bool ok = true;
  2496. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2497. while (ok) {
  2498. struct workio_cmd *wc;
  2499. if (opt_debug)
  2500. applog(LOG_DEBUG, "Popping work to work thread");
  2501. /* wait for workio_cmd sent to us, on our queue */
  2502. wc = tq_pop(mythr->q, NULL);
  2503. if (unlikely(!wc)) {
  2504. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2505. ok = false;
  2506. break;
  2507. }
  2508. /* process workio_cmd */
  2509. switch (wc->cmd) {
  2510. case WC_GET_WORK:
  2511. ok = workio_get_work(wc);
  2512. break;
  2513. case WC_SUBMIT_WORK:
  2514. ok = workio_submit_work(wc);
  2515. break;
  2516. case WC_DIE:
  2517. default:
  2518. ok = false;
  2519. break;
  2520. }
  2521. }
  2522. tq_freeze(mythr->q);
  2523. return NULL;
  2524. }
  2525. static void thread_reportin(struct thr_info *thr)
  2526. {
  2527. gettimeofday(&thr->last, NULL);
  2528. thr->cgpu->status = LIFE_WELL;
  2529. thr->getwork = false;
  2530. }
  2531. static inline void thread_reportout(struct thr_info *thr)
  2532. {
  2533. thr->getwork = true;
  2534. }
  2535. static void hashmeter(int thr_id, struct timeval *diff,
  2536. unsigned long hashes_done)
  2537. {
  2538. struct timeval temp_tv_end, total_diff;
  2539. double secs;
  2540. double local_secs;
  2541. double utility, efficiency = 0.0;
  2542. static double local_mhashes_done = 0;
  2543. static double rolling = 0;
  2544. double local_mhashes = (double)hashes_done / 1000000.0;
  2545. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2546. bool showlog = false;
  2547. /* Update the last time this thread reported in */
  2548. if (thr_id >= 0)
  2549. gettimeofday(&thr_info[thr_id].last, NULL);
  2550. /* Don't bother calculating anything if we're not displaying it */
  2551. if (opt_realquiet || !opt_log_interval)
  2552. return;
  2553. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2554. /* So we can call hashmeter from a non worker thread */
  2555. if (thr_id >= 0) {
  2556. struct thr_info *thr = &thr_info[thr_id];
  2557. double thread_rolling = 0.0;
  2558. int i;
  2559. if (opt_debug)
  2560. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2561. thr_id, hashes_done, hashes_done / secs);
  2562. /* Rolling average for each thread and each device */
  2563. decay_time(&thr->rolling, local_mhashes / secs);
  2564. for (i = 0; i < mining_threads; i++) {
  2565. struct thr_info *th = &thr_info[i];
  2566. if (th->cgpu == cgpu)
  2567. thread_rolling += th->rolling;
  2568. }
  2569. decay_time(&cgpu->rolling, thread_rolling);
  2570. cgpu->total_mhashes += local_mhashes;
  2571. // If needed, output detailed, per-device stats
  2572. if (want_per_device_stats) {
  2573. struct timeval now;
  2574. struct timeval elapsed;
  2575. gettimeofday(&now, NULL);
  2576. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2577. if (opt_log_interval <= elapsed.tv_sec) {
  2578. thr->cgpu->last_message_tv = now;
  2579. sprintf(
  2580. statusline,
  2581. "[%sPU%d (%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2582. thr->cgpu->is_gpu ? "G" : "C",
  2583. thr->cgpu->cpu_gpu,
  2584. opt_log_interval,
  2585. thr->cgpu->rolling,
  2586. thr->cgpu->total_mhashes / total_secs,
  2587. thr->cgpu->getworks,
  2588. thr->cgpu->accepted,
  2589. thr->cgpu->rejected,
  2590. thr->cgpu->hw_errors,
  2591. thr->cgpu->efficiency,
  2592. thr->cgpu->utility
  2593. );
  2594. if (!curses_active) {
  2595. printf("%s \r", statusline);
  2596. fflush(stdout);
  2597. } else
  2598. applog(LOG_INFO, "%s", statusline);
  2599. }
  2600. }
  2601. }
  2602. /* Totals are updated by all threads so can race without locking */
  2603. mutex_lock(&hash_lock);
  2604. gettimeofday(&temp_tv_end, NULL);
  2605. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2606. total_mhashes_done += local_mhashes;
  2607. local_mhashes_done += local_mhashes;
  2608. if (total_diff.tv_sec < opt_log_interval)
  2609. /* Only update the total every opt_log_interval seconds */
  2610. goto out_unlock;
  2611. showlog = true;
  2612. gettimeofday(&total_tv_end, NULL);
  2613. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2614. decay_time(&rolling, local_mhashes_done / local_secs);
  2615. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2616. total_secs = (double)total_diff.tv_sec +
  2617. ((double)total_diff.tv_usec / 1000000.0);
  2618. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2619. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2620. sprintf(statusline, "[%s(%ds):%.1f (avg):%.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  2621. want_per_device_stats ? "ALL " : "",
  2622. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2623. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2624. local_mhashes_done = 0;
  2625. out_unlock:
  2626. mutex_unlock(&hash_lock);
  2627. if (showlog) {
  2628. if (!curses_active) {
  2629. printf("%s \r", statusline);
  2630. fflush(stdout);
  2631. } else
  2632. applog(LOG_INFO, "%s", statusline);
  2633. }
  2634. }
  2635. static bool pool_active(struct pool *pool, bool pinging)
  2636. {
  2637. bool ret = false;
  2638. json_t *val;
  2639. CURL *curl;
  2640. bool rolltime;
  2641. curl = curl_easy_init();
  2642. if (unlikely(!curl)) {
  2643. applog(LOG_ERR, "CURL initialisation failed");
  2644. return false;
  2645. }
  2646. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2647. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2648. true, false, &rolltime, pool);
  2649. if (val) {
  2650. struct work *work = make_work();
  2651. bool rc;
  2652. rc = work_decode(json_object_get(val, "result"), work);
  2653. if (rc) {
  2654. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2655. pool->pool_no, pool->rpc_url);
  2656. work->pool = pool;
  2657. work->rolltime = rolltime;
  2658. if (opt_debug)
  2659. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2660. tq_push(thr_info[stage_thr_id].q, work);
  2661. total_getworks++;
  2662. pool->getwork_requested++;
  2663. inc_queued();
  2664. ret = true;
  2665. gettimeofday(&pool->tv_idle, NULL);
  2666. } else {
  2667. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2668. pool->pool_no, pool->rpc_url);
  2669. free_work(work);
  2670. }
  2671. json_decref(val);
  2672. } else {
  2673. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2674. pool->pool_no, pool->rpc_url);
  2675. if (!pinging)
  2676. applog(LOG_WARNING, "Pool down, URL or credentials invalid");
  2677. }
  2678. curl_easy_cleanup(curl);
  2679. return ret;
  2680. }
  2681. static void pool_died(struct pool *pool)
  2682. {
  2683. if (!pool_tset(pool, &pool->idle)) {
  2684. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2685. gettimeofday(&pool->tv_idle, NULL);
  2686. switch_pools(NULL);
  2687. }
  2688. }
  2689. static void pool_resus(struct pool *pool)
  2690. {
  2691. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  2692. if (pool->prio < current_pool()->prio && pool_strategy == POOL_FAILOVER)
  2693. switch_pools(NULL);
  2694. }
  2695. static bool queue_request(struct thr_info *thr, bool needed)
  2696. {
  2697. struct workio_cmd *wc;
  2698. int rq = requests_queued();
  2699. if (rq >= mining_threads)
  2700. return true;
  2701. /* fill out work request message */
  2702. wc = calloc(1, sizeof(*wc));
  2703. if (unlikely(!wc)) {
  2704. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2705. return false;
  2706. }
  2707. wc->cmd = WC_GET_WORK;
  2708. if (thr)
  2709. wc->thr = thr;
  2710. else
  2711. wc->thr = NULL;
  2712. /* If we're queueing work faster than we can stage it, consider the
  2713. * system lagging and allow work to be gathered from another pool if
  2714. * possible */
  2715. if (rq && needed && !requests_staged() && !opt_fail_only)
  2716. wc->lagging = true;
  2717. if (opt_debug)
  2718. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2719. /* send work request to workio thread */
  2720. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2721. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2722. workio_cmd_free(wc);
  2723. return false;
  2724. }
  2725. inc_queued();
  2726. return true;
  2727. }
  2728. struct work *hash_pop(const struct timespec *abstime)
  2729. {
  2730. struct work *work = NULL;
  2731. int rc;
  2732. mutex_lock(&getq->mutex);
  2733. if (HASH_COUNT(staged_work))
  2734. goto pop;
  2735. if (abstime)
  2736. rc = pthread_cond_timedwait(&getq->cond, &getq->mutex, abstime);
  2737. else
  2738. rc = pthread_cond_wait(&getq->cond, &getq->mutex);
  2739. if (rc)
  2740. goto out;
  2741. if (!HASH_COUNT(staged_work))
  2742. goto out;
  2743. pop:
  2744. work = staged_work;
  2745. HASH_DEL(staged_work, work);
  2746. out:
  2747. mutex_unlock(&getq->mutex);
  2748. return work;
  2749. }
  2750. static inline bool should_roll(struct work *work)
  2751. {
  2752. int rs;
  2753. rs = requests_staged();
  2754. if (rs >= mining_threads)
  2755. return false;
  2756. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE || !rs)
  2757. return true;
  2758. return false;
  2759. }
  2760. static inline bool can_roll(struct work *work)
  2761. {
  2762. return (work->pool && !stale_work(work) && work->rolltime &&
  2763. work->rolls < 11 && !work->clone);
  2764. }
  2765. static void roll_work(struct work *work)
  2766. {
  2767. uint32_t *work_ntime;
  2768. uint32_t ntime;
  2769. work_ntime = (uint32_t *)(work->data + 68);
  2770. ntime = be32toh(*work_ntime);
  2771. ntime++;
  2772. *work_ntime = htobe32(ntime);
  2773. local_work++;
  2774. work->rolls++;
  2775. work->blk.nonce = 0;
  2776. if (opt_debug)
  2777. applog(LOG_DEBUG, "Successfully rolled work");
  2778. }
  2779. /* Recycle the work at a higher starting res_nonce if we know the thread we're
  2780. * giving it to will not finish scanning it. We keep the master copy to be
  2781. * recycled more rapidly and discard the clone to avoid repeating work */
  2782. static bool divide_work(struct timeval *now, struct work *work, uint32_t hash_div)
  2783. {
  2784. uint64_t hash_inc;
  2785. if (work->clone)
  2786. return false;
  2787. hash_inc = MAXTHREADS / hash_div * 2;
  2788. if ((uint64_t)work->blk.nonce + hash_inc < MAXTHREADS) {
  2789. /* Okay we can divide it up */
  2790. work->blk.nonce += hash_inc;
  2791. work->cloned = true;
  2792. local_work++;
  2793. if (opt_debug)
  2794. applog(LOG_DEBUG, "Successfully divided work");
  2795. return true;
  2796. } else if (can_roll(work) && should_roll(work)) {
  2797. roll_work(work);
  2798. return true;
  2799. }
  2800. return false;
  2801. }
  2802. static bool get_work(struct work *work, bool requested, struct thr_info *thr,
  2803. const int thr_id, uint32_t hash_div)
  2804. {
  2805. struct timespec abstime = {};
  2806. struct timeval now;
  2807. struct work *work_heap;
  2808. struct pool *pool;
  2809. bool ret = false;
  2810. int failures = 0;
  2811. /* Tell the watchdog thread this thread is waiting on getwork and
  2812. * should not be restarted */
  2813. thread_reportout(thr);
  2814. retry:
  2815. pool = current_pool();
  2816. if (unlikely((!requested || requests_queued() < opt_queue) && !queue_request(thr, true))) {
  2817. applog(LOG_WARNING, "Failed to queue_request in get_work");
  2818. goto out;
  2819. }
  2820. if (!requests_staged()) {
  2821. if (can_roll(work)) {
  2822. roll_work(work);
  2823. ret = true;
  2824. goto out;
  2825. }
  2826. if (requested && requests_queued() >= mining_threads &&
  2827. !pool_tset(pool, &pool->lagging)) {
  2828. applog(LOG_WARNING, "Pool %d not providing work fast enough",
  2829. pool->pool_no);
  2830. pool->getfail_occasions++;
  2831. total_go++;
  2832. }
  2833. }
  2834. requested = false;
  2835. gettimeofday(&now, NULL);
  2836. abstime.tv_sec = now.tv_sec + 60;
  2837. if (opt_debug)
  2838. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2839. /* wait for 1st response, or get cached response */
  2840. work_heap = hash_pop(&abstime);
  2841. if (unlikely(!work_heap)) {
  2842. /* Attempt to switch pools if this one times out */
  2843. pool_died(pool);
  2844. goto retry;
  2845. }
  2846. if (stale_work(work_heap)) {
  2847. dec_queued();
  2848. discard_work(work_heap);
  2849. goto retry;
  2850. }
  2851. pool = work_heap->pool;
  2852. /* If we make it here we have succeeded in getting fresh work */
  2853. if (!work_heap->mined) {
  2854. pool_tclear(pool, &pool->lagging);
  2855. if (pool_tclear(pool, &pool->idle))
  2856. pool_resus(pool);
  2857. }
  2858. memcpy(work, work_heap, sizeof(*work));
  2859. /* Copy the res nonce back so we know to start at a higher baseline
  2860. * should we divide the same work up again. Make the work we're
  2861. * handing out be clone */
  2862. if (divide_work(&now, work_heap, hash_div)) {
  2863. if (opt_debug)
  2864. applog(LOG_DEBUG, "Pushing divided work to get queue head");
  2865. hash_push(work_heap);
  2866. work->clone = true;
  2867. } else {
  2868. dec_queued();
  2869. free_work(work_heap);
  2870. }
  2871. ret = true;
  2872. out:
  2873. if (unlikely(ret == false)) {
  2874. if ((opt_retries >= 0) && (++failures > opt_retries)) {
  2875. applog(LOG_ERR, "Failed %d times to get_work");
  2876. return ret;
  2877. }
  2878. applog(LOG_DEBUG, "Retrying after %d seconds", fail_pause);
  2879. sleep(fail_pause);
  2880. fail_pause += opt_fail_pause;
  2881. goto retry;
  2882. }
  2883. fail_pause = opt_fail_pause;
  2884. work->thr_id = thr_id;
  2885. thread_reportin(thr);
  2886. if (ret)
  2887. work->mined = true;
  2888. return ret;
  2889. }
  2890. static bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2891. {
  2892. struct workio_cmd *wc;
  2893. /* fill out work request message */
  2894. wc = calloc(1, sizeof(*wc));
  2895. if (unlikely(!wc)) {
  2896. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2897. return false;
  2898. }
  2899. wc->u.work = make_work();
  2900. wc->cmd = WC_SUBMIT_WORK;
  2901. wc->thr = thr;
  2902. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2903. if (opt_debug)
  2904. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2905. /* send solution to workio thread */
  2906. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2907. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2908. goto err_out;
  2909. }
  2910. return true;
  2911. err_out:
  2912. workio_cmd_free(wc);
  2913. return false;
  2914. }
  2915. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2916. {
  2917. work->data[64+12+0] = (nonce>>0) & 0xff;
  2918. work->data[64+12+1] = (nonce>>8) & 0xff;
  2919. work->data[64+12+2] = (nonce>>16) & 0xff;
  2920. work->data[64+12+3] = (nonce>>24) & 0xff;
  2921. /* Do one last check before attempting to submit the work */
  2922. if (!fulltest(work->data + 64, work->target))
  2923. return true;
  2924. return submit_work_sync(thr, work);
  2925. }
  2926. static void *miner_thread(void *userdata)
  2927. {
  2928. struct work *work = make_work();
  2929. struct thr_info *mythr = userdata;
  2930. const int thr_id = mythr->id;
  2931. uint32_t max_nonce = 0xffffff, total_hashes = 0;
  2932. unsigned long hashes_done = max_nonce;
  2933. bool needs_work = true;
  2934. /* Try to cycle approximately 5 times before each log update */
  2935. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  2936. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2937. bool requested = false;
  2938. uint32_t nonce_inc = max_nonce, hash_div = 1;
  2939. double hash_divfloat = 1.0;
  2940. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2941. /* Set worker threads to nice 19 and then preferentially to SCHED_IDLE
  2942. * and if that fails, then SCHED_BATCH. No need for this to be an
  2943. * error if it fails */
  2944. setpriority(PRIO_PROCESS, 0, 19);
  2945. drop_policy();
  2946. /* Cpu affinity only makes sense if the number of threads is a multiple
  2947. * of the number of CPUs */
  2948. if (!(opt_n_threads % num_processors))
  2949. affine_to_cpu(thr_id - gpu_threads, dev_from_id(thr_id));
  2950. /* Invalidate pool so it fails can_roll() test */
  2951. work->pool = NULL;
  2952. while (1) {
  2953. struct timeval tv_workstart, tv_start, tv_end, diff;
  2954. uint64_t max64;
  2955. bool rc;
  2956. if (needs_work) {
  2957. gettimeofday(&tv_workstart, NULL);
  2958. /* obtain new work from internal workio thread */
  2959. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  2960. applog(LOG_ERR, "work retrieval failed, exiting "
  2961. "mining thread %d", thr_id);
  2962. goto out;
  2963. }
  2964. needs_work = requested = false;
  2965. total_hashes = 0;
  2966. max_nonce = work->blk.nonce + hashes_done;
  2967. }
  2968. hashes_done = 0;
  2969. gettimeofday(&tv_start, NULL);
  2970. /* scan nonces for a proof-of-work hash */
  2971. switch (opt_algo) {
  2972. case ALGO_C:
  2973. rc = scanhash_c(thr_id, work->midstate, work->data + 64,
  2974. work->hash1, work->hash, work->target,
  2975. max_nonce, &hashes_done,
  2976. work->blk.nonce);
  2977. break;
  2978. #ifdef WANT_X8632_SSE2
  2979. case ALGO_SSE2_32: {
  2980. unsigned int rc5 =
  2981. scanhash_sse2_32(thr_id, work->midstate, work->data + 64,
  2982. work->hash1, work->hash,
  2983. work->target,
  2984. max_nonce, &hashes_done,
  2985. work->blk.nonce);
  2986. rc = (rc5 == -1) ? false : true;
  2987. }
  2988. break;
  2989. #endif
  2990. #ifdef WANT_X8664_SSE2
  2991. case ALGO_SSE2_64: {
  2992. unsigned int rc5 =
  2993. scanhash_sse2_64(thr_id, work->midstate, work->data + 64,
  2994. work->hash1, work->hash,
  2995. work->target,
  2996. max_nonce, &hashes_done,
  2997. work->blk.nonce);
  2998. rc = (rc5 == -1) ? false : true;
  2999. }
  3000. break;
  3001. #endif
  3002. #ifdef WANT_X8664_SSE4
  3003. case ALGO_SSE4_64: {
  3004. unsigned int rc5 =
  3005. scanhash_sse4_64(thr_id, work->midstate, work->data + 64,
  3006. work->hash1, work->hash,
  3007. work->target,
  3008. max_nonce, &hashes_done,
  3009. work->blk.nonce);
  3010. rc = (rc5 == -1) ? false : true;
  3011. }
  3012. break;
  3013. #endif
  3014. #ifdef WANT_SSE2_4WAY
  3015. case ALGO_4WAY: {
  3016. unsigned int rc4 =
  3017. ScanHash_4WaySSE2(thr_id, work->midstate, work->data + 64,
  3018. work->hash1, work->hash,
  3019. work->target,
  3020. max_nonce, &hashes_done,
  3021. work->blk.nonce);
  3022. rc = (rc4 == -1) ? false : true;
  3023. }
  3024. break;
  3025. #endif
  3026. #ifdef WANT_VIA_PADLOCK
  3027. case ALGO_VIA:
  3028. rc = scanhash_via(thr_id, work->data, work->target,
  3029. max_nonce, &hashes_done,
  3030. work->blk.nonce);
  3031. break;
  3032. #endif
  3033. case ALGO_CRYPTOPP:
  3034. rc = scanhash_cryptopp(thr_id, work->midstate, work->data + 64,
  3035. work->hash1, work->hash, work->target,
  3036. max_nonce, &hashes_done,
  3037. work->blk.nonce);
  3038. break;
  3039. #ifdef WANT_CRYPTOPP_ASM32
  3040. case ALGO_CRYPTOPP_ASM32:
  3041. rc = scanhash_asm32(thr_id, work->midstate, work->data + 64,
  3042. work->hash1, work->hash, work->target,
  3043. max_nonce, &hashes_done,
  3044. work->blk.nonce);
  3045. break;
  3046. #endif
  3047. default:
  3048. /* should never happen */
  3049. goto out;
  3050. }
  3051. /* record scanhash elapsed time */
  3052. gettimeofday(&tv_end, NULL);
  3053. timeval_subtract(&diff, &tv_end, &tv_start);
  3054. hashes_done -= work->blk.nonce;
  3055. hashmeter(thr_id, &diff, hashes_done);
  3056. total_hashes += hashes_done;
  3057. work->blk.nonce += hashes_done;
  3058. /* adjust max_nonce to meet target cycle time */
  3059. if (diff.tv_usec > 500000)
  3060. diff.tv_sec++;
  3061. if (diff.tv_sec && diff.tv_sec != cycle) {
  3062. uint64_t next_inc = ((uint64_t)hashes_done * (uint64_t)cycle) / (uint64_t)diff.tv_sec;
  3063. if (next_inc > (uint64_t)nonce_inc / 2 * 3)
  3064. next_inc = nonce_inc / 2 * 3;
  3065. nonce_inc = next_inc;
  3066. } else if (!diff.tv_sec)
  3067. nonce_inc = hashes_done * 2;
  3068. if (nonce_inc < 4)
  3069. nonce_inc = 0xffffff;
  3070. max64 = work->blk.nonce + nonce_inc;
  3071. if (max64 > 0xfffffffaULL)
  3072. max64 = 0xfffffffaULL;
  3073. max_nonce = max64;
  3074. /* if nonce found, submit work */
  3075. if (unlikely(rc)) {
  3076. if (opt_debug)
  3077. applog(LOG_DEBUG, "CPU %d found something?", dev_from_id(thr_id));
  3078. if (unlikely(!submit_work_sync(mythr, work))) {
  3079. applog(LOG_ERR, "Failed to submit_work_sync in miner_thread %d", thr_id);
  3080. break;
  3081. }
  3082. work->blk.nonce += 4;
  3083. }
  3084. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3085. if (!requested && (diff.tv_sec >= request_interval)) {
  3086. thread_reportout(mythr);
  3087. if (unlikely(!queue_request(mythr, false))) {
  3088. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  3089. goto out;
  3090. }
  3091. thread_reportin(mythr);
  3092. requested = true;
  3093. }
  3094. if (diff.tv_sec > opt_scantime) {
  3095. decay_time(&hash_divfloat , (double)((MAXTHREADS / total_hashes) ? : 1));
  3096. hash_div = hash_divfloat;
  3097. needs_work = true;
  3098. } else if (work_restart[thr_id].restart || stale_work(work) ||
  3099. work->blk.nonce >= MAXTHREADS - hashes_done)
  3100. needs_work = true;
  3101. if (unlikely(mythr->pause)) {
  3102. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3103. mythr->rolling = mythr->cgpu->rolling = 0;
  3104. if (opt_debug)
  3105. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  3106. thread_reportout(mythr);
  3107. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3108. thread_reportin(mythr);
  3109. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3110. }
  3111. }
  3112. out:
  3113. thread_reportin(mythr);
  3114. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3115. tq_freeze(mythr->q);
  3116. return NULL;
  3117. }
  3118. enum {
  3119. STAT_SLEEP_INTERVAL = 1,
  3120. STAT_CTR_INTERVAL = 10000000,
  3121. FAILURE_INTERVAL = 30,
  3122. };
  3123. #ifdef HAVE_OPENCL
  3124. static _clState *clStates[16];
  3125. static cl_int queue_poclbm_kernel(_clState *clState, dev_blk_ctx *blk)
  3126. {
  3127. cl_kernel *kernel = &clState->kernel;
  3128. cl_int status = 0;
  3129. int num = 0;
  3130. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3131. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3132. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3133. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3134. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3135. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3136. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3137. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3138. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3139. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3140. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3141. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3142. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3143. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3144. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->nonce);
  3145. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW0);
  3146. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW1);
  3147. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW2);
  3148. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW3);
  3149. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW15);
  3150. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fW01r);
  3151. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e);
  3152. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->fcty_e2);
  3153. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3154. (void *)&clState->outputBuffer);
  3155. return status;
  3156. }
  3157. static cl_int queue_phatk_kernel(_clState *clState, dev_blk_ctx *blk)
  3158. {
  3159. cl_uint vwidth = clState->preferred_vwidth;
  3160. cl_kernel *kernel = &clState->kernel;
  3161. cl_int status = 0;
  3162. int i, num = 0;
  3163. uint *nonces;
  3164. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_a);
  3165. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_b);
  3166. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_c);
  3167. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_d);
  3168. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_e);
  3169. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_f);
  3170. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_g);
  3171. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->ctx_h);
  3172. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_b);
  3173. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_c);
  3174. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_d);
  3175. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_f);
  3176. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_g);
  3177. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->cty_h);
  3178. nonces = alloca(sizeof(uint) * vwidth);
  3179. for (i = 0; i < vwidth; i++)
  3180. nonces[i] = blk->nonce + i;
  3181. status |= clSetKernelArg(*kernel, num++, vwidth * sizeof(uint), (void *)nonces);
  3182. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W16);
  3183. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->W17);
  3184. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal4_2);
  3185. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreVal0);
  3186. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW18);
  3187. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW19);
  3188. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW31);
  3189. status |= clSetKernelArg(*kernel, num++, sizeof(uint), (void *)&blk->PreW32);
  3190. status |= clSetKernelArg(*kernel, num++, sizeof(clState->outputBuffer),
  3191. (void *)&clState->outputBuffer);
  3192. return status;
  3193. }
  3194. static void set_threads_hashes(unsigned int vectors, unsigned int *threads,
  3195. unsigned int *hashes, size_t *globalThreads,
  3196. unsigned int minthreads)
  3197. {
  3198. *threads = 1 << (15 + scan_intensity);
  3199. if (*threads < minthreads)
  3200. *threads = minthreads;
  3201. *globalThreads = *threads;
  3202. *hashes = *threads * vectors;
  3203. }
  3204. static void *gpuminer_thread(void *userdata)
  3205. {
  3206. cl_int (*queue_kernel_parameters)(_clState *, dev_blk_ctx *);
  3207. const unsigned long cycle = opt_log_interval / 5 ? : 1;
  3208. struct timeval tv_start, tv_end, diff, tv_workstart;
  3209. struct thr_info *mythr = userdata;
  3210. const int thr_id = mythr->id;
  3211. uint32_t *res, *blank_res;
  3212. double gpu_ms_average = 7;
  3213. int gpu = dev_from_id(thr_id);
  3214. size_t globalThreads[1];
  3215. size_t localThreads[1];
  3216. cl_int status;
  3217. _clState *clState = clStates[thr_id];
  3218. const cl_kernel *kernel = &clState->kernel;
  3219. struct work *work = make_work();
  3220. unsigned int threads;
  3221. unsigned const int vectors = clState->preferred_vwidth;
  3222. unsigned int hashes;
  3223. unsigned int hashes_done = 0;
  3224. /* Request the next work item at 2/3 of the scantime */
  3225. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  3226. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  3227. bool requested = false;
  3228. uint32_t total_hashes = 0, hash_div = 1;
  3229. switch (chosen_kernel) {
  3230. case KL_POCLBM:
  3231. queue_kernel_parameters = &queue_poclbm_kernel;
  3232. break;
  3233. case KL_PHATK:
  3234. default:
  3235. queue_kernel_parameters = &queue_phatk_kernel;
  3236. break;
  3237. }
  3238. if (opt_dynamic) {
  3239. /* Minimise impact on desktop if we want dynamic mode */
  3240. setpriority(PRIO_PROCESS, 0, 19);
  3241. drop_policy();
  3242. }
  3243. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3244. res = calloc(BUFFERSIZE, 1);
  3245. blank_res = calloc(BUFFERSIZE, 1);
  3246. if (!res || !blank_res) {
  3247. applog(LOG_ERR, "Failed to calloc in gpuminer_thread");
  3248. goto out;
  3249. }
  3250. gettimeofday(&tv_start, NULL);
  3251. localThreads[0] = clState->work_size;
  3252. set_threads_hashes(vectors, &threads, &hashes, &globalThreads[0],
  3253. localThreads[0]);
  3254. diff.tv_sec = 0;
  3255. gettimeofday(&tv_end, NULL);
  3256. work->pool = NULL;
  3257. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_TRUE, 0,
  3258. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3259. if (unlikely(status != CL_SUCCESS))
  3260. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3261. mythr->cgpu->status = LIFE_WELL;
  3262. if (opt_debug)
  3263. applog(LOG_DEBUG, "Popping ping in gpuminer thread");
  3264. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  3265. gettimeofday(&tv_workstart, NULL);
  3266. /* obtain new work from internal workio thread */
  3267. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3268. applog(LOG_ERR, "work retrieval failed, exiting "
  3269. "gpu mining thread %d", thr_id);
  3270. goto out;
  3271. }
  3272. requested = false;
  3273. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3274. work->blk.nonce = 0;
  3275. while (1) {
  3276. struct timeval tv_gpustart, tv_gpuend;
  3277. suseconds_t gpu_us;
  3278. gettimeofday(&tv_gpustart, NULL);
  3279. timeval_subtract(&diff, &tv_gpustart, &tv_gpuend);
  3280. /* This finish flushes the readbuffer set with CL_FALSE later */
  3281. clFinish(clState->commandQueue);
  3282. gettimeofday(&tv_gpuend, NULL);
  3283. timeval_subtract(&diff, &tv_gpuend, &tv_gpustart);
  3284. gpu_us = diff.tv_sec * 1000000 + diff.tv_usec;
  3285. decay_time(&gpu_ms_average, gpu_us / 1000);
  3286. if (opt_dynamic) {
  3287. /* Try to not let the GPU be out for longer than 6ms, but
  3288. * increase intensity when the system is idle, unless
  3289. * dynamic is disabled. */
  3290. if (gpu_ms_average > 7) {
  3291. if (scan_intensity > -10)
  3292. scan_intensity--;
  3293. } else if (gpu_ms_average < 3) {
  3294. if (scan_intensity < 10)
  3295. scan_intensity++;
  3296. }
  3297. }
  3298. set_threads_hashes(vectors, &threads, &hashes, globalThreads, localThreads[0]);
  3299. if (diff.tv_sec > opt_scantime ||
  3300. work->blk.nonce >= MAXTHREADS - hashes ||
  3301. work_restart[thr_id].restart ||
  3302. stale_work(work)) {
  3303. /* Ignore any reads since we're getting new work and queue a clean buffer */
  3304. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3305. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3306. if (unlikely(status != CL_SUCCESS))
  3307. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3308. memset(res, 0, BUFFERSIZE);
  3309. gettimeofday(&tv_workstart, NULL);
  3310. if (opt_debug)
  3311. applog(LOG_DEBUG, "getwork thread %d", thr_id);
  3312. /* obtain new work from internal workio thread */
  3313. if (unlikely(!get_work(work, requested, mythr, thr_id, hash_div))) {
  3314. applog(LOG_ERR, "work retrieval failed, exiting "
  3315. "gpu mining thread %d", thr_id);
  3316. goto out;
  3317. }
  3318. requested = false;
  3319. precalc_hash(&work->blk, (uint32_t *)(work->midstate), (uint32_t *)(work->data + 64));
  3320. work_restart[thr_id].restart = 0;
  3321. /* Flushes the writebuffer set with CL_FALSE above */
  3322. clFinish(clState->commandQueue);
  3323. }
  3324. status = queue_kernel_parameters(clState, &work->blk);
  3325. if (unlikely(status != CL_SUCCESS))
  3326. { applog(LOG_ERR, "Error: clSetKernelArg of all params failed."); goto out; }
  3327. /* MAXBUFFERS entry is used as a flag to say nonces exist */
  3328. if (res[FOUND]) {
  3329. /* Clear the buffer again */
  3330. status = clEnqueueWriteBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3331. BUFFERSIZE, blank_res, 0, NULL, NULL);
  3332. if (unlikely(status != CL_SUCCESS))
  3333. { applog(LOG_ERR, "Error: clEnqueueWriteBuffer failed."); goto out; }
  3334. if (opt_debug)
  3335. applog(LOG_DEBUG, "GPU %d found something?", gpu);
  3336. postcalc_hash_async(mythr, work, res);
  3337. memset(res, 0, BUFFERSIZE);
  3338. clFinish(clState->commandQueue);
  3339. }
  3340. status = clEnqueueNDRangeKernel(clState->commandQueue, *kernel, 1, NULL,
  3341. globalThreads, localThreads, 0, NULL, NULL);
  3342. if (unlikely(status != CL_SUCCESS))
  3343. { applog(LOG_ERR, "Error: Enqueueing kernel onto command queue. (clEnqueueNDRangeKernel)"); goto out; }
  3344. status = clEnqueueReadBuffer(clState->commandQueue, clState->outputBuffer, CL_FALSE, 0,
  3345. BUFFERSIZE, res, 0, NULL, NULL);
  3346. if (unlikely(status != CL_SUCCESS))
  3347. { applog(LOG_ERR, "Error: clEnqueueReadBuffer failed. (clEnqueueReadBuffer)"); goto out;}
  3348. gettimeofday(&tv_end, NULL);
  3349. timeval_subtract(&diff, &tv_end, &tv_start);
  3350. hashes_done += hashes;
  3351. total_hashes += hashes;
  3352. work->blk.nonce += hashes;
  3353. if (diff.tv_sec >= cycle) {
  3354. hashmeter(thr_id, &diff, hashes_done);
  3355. gettimeofday(&tv_start, NULL);
  3356. hashes_done = 0;
  3357. }
  3358. timeval_subtract(&diff, &tv_end, &tv_workstart);
  3359. if (!requested) {
  3360. #if 0
  3361. if (diff.tv_sec > request_interval)
  3362. hash_div = (MAXTHREADS / total_hashes) ? : 1;
  3363. #endif
  3364. if (diff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  3365. thread_reportout(mythr);
  3366. if (unlikely(!queue_request(mythr, false))) {
  3367. applog(LOG_ERR, "Failed to queue_request in gpuminer_thread %d", thr_id);
  3368. goto out;
  3369. }
  3370. thread_reportin(mythr);
  3371. requested = true;
  3372. }
  3373. }
  3374. if (unlikely(!gpu_devices[gpu] || mythr->pause)) {
  3375. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  3376. mythr->rolling = mythr->cgpu->rolling = 0;
  3377. if (opt_debug)
  3378. applog(LOG_DEBUG, "Popping wakeup ping in gpuminer thread");
  3379. thread_reportout(mythr);
  3380. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  3381. thread_reportin(mythr);
  3382. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  3383. }
  3384. }
  3385. out:
  3386. clReleaseCommandQueue(clState->commandQueue);
  3387. clReleaseKernel(clState->kernel);
  3388. clReleaseProgram(clState->program);
  3389. clReleaseContext(clState->context);
  3390. thread_reportin(mythr);
  3391. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  3392. tq_freeze(mythr->q);
  3393. return NULL;
  3394. }
  3395. #endif /* HAVE_OPENCL */
  3396. /* Stage another work item from the work returned in a longpoll */
  3397. static void convert_to_work(json_t *val, bool rolltime)
  3398. {
  3399. struct work *work;
  3400. bool rc;
  3401. work = make_work();
  3402. rc= work_decode(json_object_get(val, "result"), work);
  3403. if (unlikely(!rc)) {
  3404. applog(LOG_ERR, "Could not convert longpoll data to work");
  3405. return;
  3406. }
  3407. work->pool = current_pool();
  3408. work->rolltime = rolltime;
  3409. if (opt_debug)
  3410. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  3411. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work)))
  3412. applog(LOG_ERR, "Could not tq_push work in convert_to_work");
  3413. else if (opt_debug)
  3414. applog(LOG_DEBUG, "Converted longpoll data to work");
  3415. }
  3416. static void *longpoll_thread(void *userdata)
  3417. {
  3418. struct thr_info *mythr = userdata;
  3419. CURL *curl = NULL;
  3420. char *copy_start, *hdr_path, *lp_url = NULL;
  3421. bool need_slash = false;
  3422. int failures = 0;
  3423. struct pool *pool = current_pool();
  3424. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3425. curl = curl_easy_init();
  3426. if (unlikely(!curl)) {
  3427. applog(LOG_ERR, "CURL initialisation failed");
  3428. goto out;
  3429. }
  3430. tq_pop(mythr->q, NULL);
  3431. if (!pool->hdr_path) {
  3432. applog(LOG_WARNING, "No long-poll found on this server");
  3433. goto out;
  3434. }
  3435. hdr_path = pool->hdr_path;
  3436. /* full URL */
  3437. if (strstr(hdr_path, "://")) {
  3438. lp_url = hdr_path;
  3439. hdr_path = NULL;
  3440. }
  3441. /* absolute path, on current server */
  3442. else {
  3443. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  3444. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  3445. need_slash = true;
  3446. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  3447. if (!lp_url)
  3448. goto out;
  3449. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  3450. }
  3451. have_longpoll = true;
  3452. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  3453. while (1) {
  3454. struct timeval start, end;
  3455. bool rolltime;
  3456. json_t *val;
  3457. gettimeofday(&start, NULL);
  3458. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  3459. false, true, &rolltime, pool);
  3460. if (likely(val)) {
  3461. /* Keep track of who ordered a restart_threads to make
  3462. * sure it's only done once per new block */
  3463. if (block_changed != BLOCK_DETECT) {
  3464. block_changed = BLOCK_LP;
  3465. applog(LOG_WARNING, "LONGPOLL detected new block on network, waiting on fresh work");
  3466. } else {
  3467. applog(LOG_WARNING, "LONGPOLL received after new block already detected");
  3468. block_changed = BLOCK_NONE;
  3469. }
  3470. convert_to_work(val, rolltime);
  3471. failures = 0;
  3472. json_decref(val);
  3473. } else {
  3474. /* Some pools regularly drop the longpoll request so
  3475. * only see this as longpoll failure if it happens
  3476. * immediately and just restart it the rest of the
  3477. * time. */
  3478. gettimeofday(&end, NULL);
  3479. if (end.tv_sec - start.tv_sec > 30)
  3480. continue;
  3481. if (failures++ < 10) {
  3482. sleep(30);
  3483. applog(LOG_WARNING,
  3484. "longpoll failed for %s, sleeping for 30s", lp_url);
  3485. } else {
  3486. applog(LOG_ERR,
  3487. "longpoll failed for %s, ending thread", lp_url);
  3488. goto out;
  3489. }
  3490. }
  3491. }
  3492. out:
  3493. have_longpoll = false;
  3494. tq_freeze(mythr->q);
  3495. if (curl)
  3496. curl_easy_cleanup(curl);
  3497. return NULL;
  3498. }
  3499. static void stop_longpoll(void)
  3500. {
  3501. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3502. tq_freeze(thr->q);
  3503. pthread_cancel(*thr->pth);
  3504. have_longpoll = false;
  3505. }
  3506. static void start_longpoll(void)
  3507. {
  3508. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3509. tq_thaw(thr->q);
  3510. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3511. quit(1, "longpoll thread create failed");
  3512. pthread_detach(*thr->pth);
  3513. if (opt_debug)
  3514. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3515. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3516. }
  3517. static void restart_longpoll(void)
  3518. {
  3519. stop_longpoll();
  3520. if (want_longpoll)
  3521. start_longpoll();
  3522. }
  3523. static void *reinit_cpu(void *userdata)
  3524. {
  3525. pthread_detach(pthread_self());
  3526. #if 0
  3527. struct cgpu_info *cgpu = (struct cgpu_info *)userdata;
  3528. int cpu = cgpu->cpu_gpu;
  3529. long thr_id = ....(long)userdata;
  3530. struct thr_info *thr = &thr_info[thr_id];
  3531. int cpu = dev_from_id(thr_id);
  3532. cpus[cpu].alive = false;
  3533. thr->rolling = thr->cgpu->rolling = 0;
  3534. tq_freeze(thr->q);
  3535. if (!pthread_cancel(*thr->pth))
  3536. pthread_join(*thr->pth, NULL);
  3537. free(thr->q);
  3538. thr->q = tq_new();
  3539. if (!thr->q)
  3540. quit(1, "Failed to tq_new in reinit_cputhread");
  3541. applog(LOG_INFO, "Reinit CPU thread %d", thr_id);
  3542. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr))) {
  3543. applog(LOG_ERR, "thread %d create failed", thr_id);
  3544. return NULL;
  3545. }
  3546. tq_push(thr->q, &ping);
  3547. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3548. #endif
  3549. return NULL;
  3550. }
  3551. #ifdef HAVE_OPENCL
  3552. /* We have only one thread that ever re-initialises GPUs, thus if any GPU
  3553. * init command fails due to a completely wedged GPU, the thread will never
  3554. * return, unable to harm other GPUs. If it does return, it means we only had
  3555. * a soft failure and then the reinit_gpu thread is ready to tackle another
  3556. * GPU */
  3557. static void *reinit_gpu(void *userdata)
  3558. {
  3559. struct thr_info *mythr = userdata;
  3560. struct cgpu_info *cgpu;
  3561. struct thr_info *thr;
  3562. struct timeval now;
  3563. char name[256];
  3564. int thr_id;
  3565. int gpu;
  3566. pthread_detach(pthread_self());
  3567. select_cgpu:
  3568. cgpu = tq_pop(mythr->q, NULL);
  3569. if (!cgpu)
  3570. goto out;
  3571. if (clDevicesNum() != nDevs) {
  3572. applog(LOG_WARNING, "Hardware not reporting same number of active devices, will not attempt to restart GPU");
  3573. goto out;
  3574. }
  3575. gpu = cgpu->cpu_gpu;
  3576. gpu_devices[gpu] = false;
  3577. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3578. if (dev_from_id(thr_id) != gpu)
  3579. continue;
  3580. thr = &thr_info[thr_id];
  3581. thr->rolling = thr->cgpu->rolling = 0;
  3582. /* Reports the last time we tried to revive a sick GPU */
  3583. gettimeofday(&thr->sick, NULL);
  3584. if (!pthread_cancel(*thr->pth)) {
  3585. applog(LOG_WARNING, "Thread %d still exists, killing it off", thr_id);
  3586. } else
  3587. applog(LOG_WARNING, "Thread %d no longer exists", thr_id);
  3588. }
  3589. gpu_devices[gpu] = true;
  3590. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3591. if (dev_from_id(thr_id) != gpu)
  3592. continue;
  3593. thr = &thr_info[thr_id];
  3594. /* Lose this ram cause we may get stuck here! */
  3595. //tq_freeze(thr->q);
  3596. thr->q = tq_new();
  3597. if (!thr->q)
  3598. quit(1, "Failed to tq_new in reinit_gpu");
  3599. /* Lose this ram cause we may dereference in the dying thread! */
  3600. //free(clState);
  3601. applog(LOG_INFO, "Reinit GPU thread %d", thr_id);
  3602. clStates[thr_id] = initCl(gpu, name, sizeof(name));
  3603. if (!clStates[thr_id]) {
  3604. applog(LOG_ERR, "Failed to reinit GPU thread %d", thr_id);
  3605. goto select_cgpu;
  3606. }
  3607. applog(LOG_INFO, "initCl() finished. Found %s", name);
  3608. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr))) {
  3609. applog(LOG_ERR, "thread %d create failed", thr_id);
  3610. return NULL;
  3611. }
  3612. applog(LOG_WARNING, "Thread %d restarted", thr_id);
  3613. }
  3614. gettimeofday(&now, NULL);
  3615. get_datestamp(cgpu->init, &now);
  3616. for (thr_id = 0; thr_id < gpu_threads; thr_id ++) {
  3617. if (dev_from_id(thr_id) != gpu)
  3618. continue;
  3619. thr = &thr_info[thr_id];
  3620. tq_push(thr->q, &ping);
  3621. }
  3622. goto select_cgpu;
  3623. out:
  3624. return NULL;
  3625. }
  3626. #else
  3627. static void *reinit_gpu(void *userdata)
  3628. {
  3629. }
  3630. #endif
  3631. static void reinit_device(struct cgpu_info *cgpu)
  3632. {
  3633. if (cgpu->is_gpu)
  3634. tq_push(thr_info[gpur_thr_id].q, cgpu);
  3635. else
  3636. tq_push(thr_info[cpur_thr_id].q, cgpu);
  3637. }
  3638. /* Determine which are the first threads belonging to a device and if they're
  3639. * active */
  3640. static bool active_device(int thr_id)
  3641. {
  3642. if (thr_id < gpu_threads) {
  3643. if (thr_id >= total_devices)
  3644. return false;
  3645. if (!gpu_devices[dev_from_id(thr_id)])
  3646. return false;
  3647. } else if (thr_id > gpu_threads + num_processors)
  3648. return false;
  3649. return true;
  3650. }
  3651. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3652. * the screen at regular intervals, and restarts threads if they appear to have
  3653. * died. */
  3654. static void *watchdog_thread(void *userdata)
  3655. {
  3656. const unsigned int interval = opt_log_interval / 2 ? : 1;
  3657. static struct timeval rotate_tv;
  3658. struct timeval zero_tv;
  3659. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3660. memset(&zero_tv, 0, sizeof(struct timeval));
  3661. gettimeofday(&rotate_tv, NULL);
  3662. while (1) {
  3663. int i;
  3664. struct timeval now;
  3665. sleep(interval);
  3666. if (requests_queued() < opt_queue)
  3667. queue_request(NULL, false);
  3668. hashmeter(-1, &zero_tv, 0);
  3669. if (curses_active_locked()) {
  3670. for (i = 0; i < mining_threads; i++)
  3671. curses_print_status(i);
  3672. if (!change_logwinsize()) {
  3673. redrawwin(statuswin);
  3674. redrawwin(logwin);
  3675. }
  3676. unlock_curses();
  3677. }
  3678. gettimeofday(&now, NULL);
  3679. for (i = 0; i < total_pools; i++) {
  3680. struct pool *pool = pools[i];
  3681. if (!pool->enabled)
  3682. continue;
  3683. /* Test pool is idle once every minute */
  3684. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3685. gettimeofday(&pool->tv_idle, NULL);
  3686. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3687. pool_resus(pool);
  3688. }
  3689. }
  3690. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3691. gettimeofday(&rotate_tv, NULL);
  3692. switch_pools(NULL);
  3693. }
  3694. if (!sched_paused && !should_run()) {
  3695. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  3696. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3697. if (!schedstart.enable) {
  3698. quit(0, "Terminating execution as planned");
  3699. break;
  3700. }
  3701. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  3702. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3703. sched_paused = true;
  3704. for (i = 0; i < mining_threads; i++) {
  3705. struct thr_info *thr;
  3706. thr = &thr_info[i];
  3707. thr->pause = true;
  3708. }
  3709. } else if (sched_paused && should_run()) {
  3710. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  3711. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3712. if (schedstop.enable)
  3713. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  3714. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3715. sched_paused = false;
  3716. for (i = 0; i < mining_threads; i++) {
  3717. struct thr_info *thr;
  3718. thr = &thr_info[i];
  3719. /* Don't touch disabled GPUs */
  3720. if (thr->cgpu->is_gpu && !gpu_devices[thr->cgpu->cpu_gpu])
  3721. continue;
  3722. thr->pause = false;
  3723. tq_push(thr->q, &ping);
  3724. }
  3725. }
  3726. for (i = 0; i < gpu_threads; i++) {
  3727. struct thr_info *thr;
  3728. int gpu;
  3729. /* Use only one thread per device to determine if the GPU is healthy */
  3730. if (i >= nDevs)
  3731. break;
  3732. thr = &thr_info[i];
  3733. gpu = thr->cgpu->cpu_gpu;
  3734. /* Thread is waiting on getwork or disabled */
  3735. if (thr->getwork || !gpu_devices[gpu])
  3736. continue;
  3737. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3738. applog(LOG_ERR, "Thread %d recovered, GPU %d declared WELL!", i, gpu);
  3739. gpus[gpu].status = LIFE_WELL;
  3740. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3741. thr->rolling = thr->cgpu->rolling = 0;
  3742. gpus[gpu].status = LIFE_SICK;
  3743. applog(LOG_ERR, "Thread %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3744. gettimeofday(&thr->sick, NULL);
  3745. if (opt_restart) {
  3746. applog(LOG_ERR, "Attempting to restart GPU");
  3747. reinit_device(thr->cgpu);
  3748. }
  3749. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  3750. gpus[gpu].status = LIFE_DEAD;
  3751. applog(LOG_ERR, "Thread %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  3752. } else if (now.tv_sec - thr->sick.tv_sec > 60 && gpus[i].status == LIFE_SICK) {
  3753. /* Attempt to restart a GPU once every minute */
  3754. gettimeofday(&thr->sick, NULL);
  3755. if (opt_restart)
  3756. reinit_device(thr->cgpu);
  3757. }
  3758. }
  3759. }
  3760. return NULL;
  3761. }
  3762. static void log_print_status(int thr_id)
  3763. {
  3764. struct cgpu_info *cgpu;
  3765. cgpu = thr_info[thr_id].cgpu;
  3766. applog(LOG_WARNING, " %sPU %d: [%.1f / %.1f Mh/s] [Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m]",
  3767. cgpu->is_gpu ? "G" : "C", cgpu->cpu_gpu, cgpu->rolling,
  3768. cgpu->total_mhashes / total_secs, cgpu->getworks,
  3769. cgpu->accepted, cgpu->rejected, cgpu->hw_errors,
  3770. cgpu->efficiency, cgpu->utility);
  3771. }
  3772. static void print_summary(void)
  3773. {
  3774. struct timeval diff;
  3775. int hours, mins, secs, i;
  3776. double utility, efficiency = 0.0;
  3777. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3778. hours = diff.tv_sec / 3600;
  3779. mins = (diff.tv_sec % 3600) / 60;
  3780. secs = diff.tv_sec % 60;
  3781. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3782. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3783. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  3784. applog(LOG_WARNING, "Started at %s", datestamp);
  3785. if (opt_n_threads)
  3786. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  3787. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  3788. if (total_secs)
  3789. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  3790. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  3791. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  3792. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  3793. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  3794. if (total_accepted || total_rejected)
  3795. applog(LOG_WARNING, "Reject ratio: %.1f", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3796. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  3797. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  3798. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  3799. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  3800. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  3801. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  3802. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  3803. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  3804. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  3805. if (total_pools > 1) {
  3806. for (i = 0; i < total_pools; i++) {
  3807. struct pool *pool = pools[i];
  3808. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  3809. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  3810. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  3811. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  3812. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  3813. if (pool->accepted || pool->rejected)
  3814. applog(LOG_WARNING, " Reject ratio: %.1f", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3815. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3816. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  3817. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  3818. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  3819. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  3820. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  3821. }
  3822. }
  3823. applog(LOG_WARNING, "Summary of per device statistics:\n");
  3824. for (i = 0; i < mining_threads; i++) {
  3825. if (active_device(i))
  3826. log_print_status(i);
  3827. }
  3828. if (opt_shares)
  3829. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  3830. fflush(stdout);
  3831. fflush(stderr);
  3832. if (opt_shares > total_accepted)
  3833. quit(1, "Did not successfully mine as many shares as were requested.");
  3834. }
  3835. void quit(int status, const char *format, ...)
  3836. {
  3837. va_list ap;
  3838. disable_curses();
  3839. if (!opt_realquiet && successful_connect)
  3840. print_summary();
  3841. if (format) {
  3842. va_start(ap, format);
  3843. vfprintf(stderr, format, ap);
  3844. va_end(ap);
  3845. }
  3846. fprintf(stderr, "\n");
  3847. fflush(stderr);
  3848. exit(status);
  3849. }
  3850. char *curses_input(const char *query)
  3851. {
  3852. char *input;
  3853. echo();
  3854. input = malloc(255);
  3855. if (!input)
  3856. quit(1, "Failed to malloc input");
  3857. leaveok(logwin, false);
  3858. wlogprint("%s: ", query);
  3859. wgetnstr(logwin, input, 255);
  3860. if (!strlen(input))
  3861. strcpy(input, "-1");
  3862. leaveok(logwin, true);
  3863. noecho();
  3864. return input;
  3865. }
  3866. static bool input_pool(bool live)
  3867. {
  3868. char *url = NULL, *user = NULL, *pass = NULL;
  3869. struct pool *pool = NULL;
  3870. bool ret = false;
  3871. immedok(logwin, true);
  3872. if (total_pools == MAX_POOLS) {
  3873. wlogprint("Reached maximum number of pools.\n");
  3874. goto out;
  3875. }
  3876. wlogprint("Input server details.\n");
  3877. url = curses_input("URL");
  3878. if (!url)
  3879. goto out;
  3880. if (strncmp(url, "http://", 7) &&
  3881. strncmp(url, "https://", 8)) {
  3882. char *httpinput;
  3883. httpinput = malloc(255);
  3884. if (!httpinput)
  3885. quit(1, "Failed to malloc httpinput");
  3886. strcpy(httpinput, "http://");
  3887. strncat(httpinput, url, 248);
  3888. free(url);
  3889. url = httpinput;
  3890. }
  3891. user = curses_input("Username");
  3892. if (!user)
  3893. goto out;
  3894. pass = curses_input("Password");
  3895. if (!pass)
  3896. goto out;
  3897. pool = calloc(sizeof(struct pool), 1);
  3898. if (!pool)
  3899. quit(1, "Failed to realloc pools in input_pool");
  3900. pool->pool_no = total_pools;
  3901. pool->prio = total_pools;
  3902. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3903. quit (1, "Failed to pthread_mutex_init in input_pool");
  3904. pool->rpc_url = url;
  3905. pool->rpc_user = user;
  3906. pool->rpc_pass = pass;
  3907. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3908. if (!pool->rpc_userpass)
  3909. quit(1, "Failed to malloc userpass");
  3910. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3911. pool->tv_idle.tv_sec = ~0UL;
  3912. /* Test the pool is not idle if we're live running, otherwise
  3913. * it will be tested separately */
  3914. ret = true;
  3915. pool->enabled = true;
  3916. if (live && !pool_active(pool, false))
  3917. pool->idle = true;
  3918. pools[total_pools++] = pool;
  3919. out:
  3920. immedok(logwin, false);
  3921. if (!ret) {
  3922. if (url)
  3923. free(url);
  3924. if (user)
  3925. free(user);
  3926. if (pass)
  3927. free(pass);
  3928. if (pool)
  3929. free(pool);
  3930. }
  3931. return ret;
  3932. }
  3933. #if defined(unix)
  3934. static void fork_monitor()
  3935. {
  3936. // Make a pipe: [readFD, writeFD]
  3937. int pfd[2];
  3938. int r = pipe(pfd);
  3939. if (r<0) {
  3940. perror("pipe - failed to create pipe for --monitor");
  3941. exit(1);
  3942. }
  3943. // Make stderr write end of pipe
  3944. fflush(stderr);
  3945. r = dup2(pfd[1], 2);
  3946. if (r<0) {
  3947. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3948. exit(1);
  3949. }
  3950. r = close(pfd[1]);
  3951. if (r<0) {
  3952. perror("close - failed to close write end of pipe for --monitor");
  3953. exit(1);
  3954. }
  3955. // Don't allow a dying monitor to kill the main process
  3956. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3957. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3958. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3959. perror("signal - failed to edit signal mask for --monitor");
  3960. exit(1);
  3961. }
  3962. // Fork a child process
  3963. r = fork();
  3964. if (r<0) {
  3965. perror("fork - failed to fork child process for --monitor");
  3966. exit(1);
  3967. }
  3968. // Child: launch monitor command
  3969. if (0==r) {
  3970. // Make stdin read end of pipe
  3971. r = dup2(pfd[0], 0);
  3972. if (r<0) {
  3973. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3974. exit(1);
  3975. }
  3976. close(pfd[0]);
  3977. if (r<0) {
  3978. perror("close - in child, failed to close read end of pipe for --monitor");
  3979. exit(1);
  3980. }
  3981. // Launch user specified command
  3982. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3983. perror("execl - in child failed to exec user specified command for --monitor");
  3984. exit(1);
  3985. }
  3986. // Parent: clean up unused fds and bail
  3987. r = close(pfd[0]);
  3988. if (r<0) {
  3989. perror("close - failed to close read end of pipe for --monitor");
  3990. exit(1);
  3991. }
  3992. }
  3993. #endif // defined(unix)
  3994. static void enable_curses(void) {
  3995. int x,y;
  3996. lock_curses();
  3997. if (curses_active) {
  3998. unlock_curses();
  3999. return;
  4000. }
  4001. mainwin = initscr();
  4002. getmaxyx(mainwin, y, x);
  4003. statuswin = newwin(logstart, x, 0, 0);
  4004. leaveok(statuswin, true);
  4005. logwin = newwin(y - logcursor, 0, logcursor, 0);
  4006. idlok(logwin, true);
  4007. scrollok(logwin, true);
  4008. leaveok(logwin, true);
  4009. cbreak();
  4010. noecho();
  4011. curses_active = true;
  4012. unlock_curses();
  4013. }
  4014. int main (int argc, char *argv[])
  4015. {
  4016. unsigned int i, pools_active = 0;
  4017. struct block *block, *tmpblock;
  4018. struct work *work, *tmpwork;
  4019. struct sigaction handler;
  4020. struct thr_info *thr;
  4021. char name[256];
  4022. /* This dangerous functions tramples random dynamically allocated
  4023. * variables so do it before anything at all */
  4024. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  4025. quit(1, "Failed to curl_global_init");
  4026. if (unlikely(pthread_mutex_init(&hash_lock, NULL)))
  4027. quit(1, "Failed to pthread_mutex_init");
  4028. if (unlikely(pthread_mutex_init(&qd_lock, NULL)))
  4029. quit(1, "Failed to pthread_mutex_init");
  4030. if (unlikely(pthread_mutex_init(&stgd_lock, NULL)))
  4031. quit(1, "Failed to pthread_mutex_init");
  4032. if (unlikely(pthread_mutex_init(&curses_lock, NULL)))
  4033. quit(1, "Failed to pthread_mutex_init");
  4034. if (unlikely(pthread_mutex_init(&control_lock, NULL)))
  4035. quit(1, "Failed to pthread_mutex_init");
  4036. if (unlikely(pthread_rwlock_init(&blk_lock, NULL)))
  4037. quit(1, "Failed to pthread_rwlock_init");
  4038. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  4039. init_max_name_len();
  4040. handler.sa_handler = &sighandler;
  4041. sigaction(SIGTERM, &handler, &termhandler);
  4042. sigaction(SIGINT, &handler, &inthandler);
  4043. opt_kernel_path = malloc(PATH_MAX);
  4044. strcpy(opt_kernel_path, CGMINER_PREFIX);
  4045. // Hack to make cgminer silent when called recursively on WIN32
  4046. int skip_to_bench = 0;
  4047. #if defined(WIN32)
  4048. char buf[32];
  4049. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  4050. skip_to_bench = 1;
  4051. #endif // defined(WIN32)
  4052. block = calloc(sizeof(struct block), 1);
  4053. if (unlikely(!block))
  4054. quit (1, "main OOM");
  4055. for (i = 0; i < 36; i++)
  4056. strcat(block->hash, "0");
  4057. HASH_ADD_STR(blocks, hash, block);
  4058. strcpy(current_block, block->hash);
  4059. // Reckon number of cores in the box
  4060. #if defined(WIN32)
  4061. DWORD system_am;
  4062. DWORD process_am;
  4063. BOOL ok = GetProcessAffinityMask(
  4064. GetCurrentProcess(),
  4065. &system_am,
  4066. &process_am
  4067. );
  4068. if (!ok) {
  4069. applog(LOG_ERR, "couldn't figure out number of processors :(");
  4070. num_processors = 1;
  4071. } else {
  4072. size_t n = 32;
  4073. num_processors = 0;
  4074. while (n--)
  4075. if (process_am & (1<<n))
  4076. ++num_processors;
  4077. }
  4078. #else
  4079. num_processors = sysconf(_SC_NPROCESSORS_ONLN);
  4080. #endif /* !WIN32 */
  4081. opt_n_threads = num_processors;
  4082. #ifdef HAVE_OPENCL
  4083. if (!skip_to_bench) {
  4084. for (i = 0; i < 16; i++)
  4085. gpu_devices[i] = false;
  4086. nDevs = clDevicesNum();
  4087. if (nDevs < 0) {
  4088. applog(LOG_ERR, "clDevicesNum returned error, none usable");
  4089. nDevs = 0;
  4090. }
  4091. }
  4092. #endif
  4093. /* parse command line */
  4094. opt_register_table(opt_config_table,
  4095. "Options for both config file and command line");
  4096. opt_register_table(opt_cmdline_table,
  4097. "Options for command line only");
  4098. opt_parse(&argc, argv, applog_and_exit);
  4099. if (argc != 1)
  4100. quit(1, "Unexpected extra commandline arguments");
  4101. applog(LOG_WARNING, "Started %s", packagename);
  4102. if (opt_nogpu)
  4103. nDevs = 0;
  4104. if (nDevs && !opt_usecpu)
  4105. opt_n_threads = 0;
  4106. strcat(opt_kernel_path, "/");
  4107. if (want_per_device_stats)
  4108. opt_log_output = true;
  4109. if (0<=opt_bench_algo) {
  4110. double rate = bench_algo_stage3(opt_bench_algo);
  4111. if (!skip_to_bench) {
  4112. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  4113. } else {
  4114. // Write result to shared memory for parent
  4115. #if defined(WIN32)
  4116. char unique_name[64];
  4117. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  4118. HANDLE map_handle = CreateFileMapping(
  4119. INVALID_HANDLE_VALUE, // use paging file
  4120. NULL, // default security attributes
  4121. PAGE_READWRITE, // read/write access
  4122. 0, // size: high 32-bits
  4123. 4096, // size: low 32-bits
  4124. unique_name // name of map object
  4125. );
  4126. if (NULL!=map_handle) {
  4127. void *shared_mem = MapViewOfFile(
  4128. map_handle, // object to map view of
  4129. FILE_MAP_WRITE, // read/write access
  4130. 0, // high offset: map from
  4131. 0, // low offset: beginning
  4132. 0 // default: map entire file
  4133. );
  4134. if (NULL!=shared_mem)
  4135. CopyMemory(shared_mem, &rate, sizeof(rate));
  4136. (void)UnmapViewOfFile(shared_mem);
  4137. }
  4138. (void)CloseHandle(map_handle);
  4139. }
  4140. #endif
  4141. }
  4142. exit(0);
  4143. }
  4144. if (opt_kernel) {
  4145. if (strcmp(opt_kernel, "poclbm") && strcmp(opt_kernel, "phatk"))
  4146. quit(1, "Invalid kernel name specified - must be poclbm or phatk");
  4147. if (!strcmp(opt_kernel, "poclbm"))
  4148. chosen_kernel = KL_POCLBM;
  4149. else
  4150. chosen_kernel = KL_PHATK;
  4151. } else
  4152. chosen_kernel = KL_NONE;
  4153. gpu_threads = nDevs * opt_g_threads;
  4154. if (total_devices) {
  4155. if (total_devices > nDevs)
  4156. quit(1, "More devices specified than exist");
  4157. for (i = 0; i < 16; i++)
  4158. if (gpu_devices[i] && i + 1 > nDevs)
  4159. quit (1, "Command line options set a device that doesn't exist");
  4160. } else {
  4161. for (i = 0; i < nDevs; i++)
  4162. gpu_devices[i] = true;
  4163. total_devices = nDevs;
  4164. }
  4165. if (!gpu_threads && !forced_n_threads) {
  4166. /* Maybe they turned GPU off; restore default CPU threads. */
  4167. opt_n_threads = num_processors;
  4168. }
  4169. if (!opt_n_threads && ! gpu_threads)
  4170. quit(1, "All devices disabled, cannot mine!");
  4171. logcursor = 8;
  4172. gpucursor = logcursor;
  4173. cpucursor = gpucursor + nDevs;
  4174. logstart = cpucursor + (opt_n_threads ? num_processors : 0) + 1;
  4175. logcursor = logstart + 1;
  4176. if (opt_realquiet)
  4177. use_curses = false;
  4178. if (!total_pools) {
  4179. enable_curses();
  4180. applog(LOG_WARNING, "Need to specify at least one pool server.");
  4181. if (!input_pool(false))
  4182. quit(1, "Pool setup failed");
  4183. if (!use_curses)
  4184. disable_curses();
  4185. }
  4186. for (i = 0; i < total_pools; i++) {
  4187. struct pool *pool = pools[i];
  4188. if (!pool->rpc_userpass) {
  4189. if (!pool->rpc_user || !pool->rpc_pass)
  4190. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  4191. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  4192. if (!pool->rpc_userpass)
  4193. quit(1, "Failed to malloc userpass");
  4194. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  4195. } else {
  4196. pool->rpc_user = malloc(strlen(pool->rpc_userpass));
  4197. if (!pool->rpc_user)
  4198. quit(1, "Failed to malloc user");
  4199. strcpy(pool->rpc_user, pool->rpc_userpass);
  4200. pool->rpc_user = strtok(pool->rpc_user, ":");
  4201. if (!pool->rpc_user)
  4202. quit(1, "Failed to find colon delimiter in userpass");
  4203. }
  4204. }
  4205. /* Set the currentpool to pool 0 */
  4206. currentpool = pools[0];
  4207. #ifdef HAVE_SYSLOG_H
  4208. if (use_syslog)
  4209. openlog(PACKAGE, LOG_PID, LOG_USER);
  4210. #endif
  4211. #if defined(unix)
  4212. if (opt_stderr_cmd)
  4213. fork_monitor();
  4214. #endif // defined(unix)
  4215. mining_threads = opt_n_threads + gpu_threads;
  4216. total_threads = mining_threads + 7;
  4217. work_restart = calloc(total_threads, sizeof(*work_restart));
  4218. if (!work_restart)
  4219. quit(1, "Failed to calloc work_restart");
  4220. thr_info = calloc(total_threads, sizeof(*thr));
  4221. if (!thr_info)
  4222. quit(1, "Failed to calloc thr_info");
  4223. /* init workio thread info */
  4224. work_thr_id = mining_threads;
  4225. thr = &thr_info[work_thr_id];
  4226. thr->id = work_thr_id;
  4227. thr->q = tq_new();
  4228. if (!thr->q)
  4229. quit(1, "Failed to tq_new");
  4230. /* start work I/O thread */
  4231. if (thr_info_create(thr, NULL, workio_thread, thr))
  4232. quit(1, "workio thread create failed");
  4233. /* init longpoll thread info */
  4234. longpoll_thr_id = mining_threads + 1;
  4235. thr = &thr_info[longpoll_thr_id];
  4236. thr->id = longpoll_thr_id;
  4237. thr->q = tq_new();
  4238. if (!thr->q)
  4239. quit(1, "Failed to tq_new");
  4240. if (opt_n_threads ) {
  4241. cpus = calloc(num_processors, sizeof(struct cgpu_info));
  4242. if (unlikely(!cpus))
  4243. quit(1, "Failed to calloc cpus");
  4244. }
  4245. if (gpu_threads) {
  4246. gpus = calloc(nDevs, sizeof(struct cgpu_info));
  4247. if (unlikely(!gpus))
  4248. quit(1, "Failed to calloc gpus");
  4249. }
  4250. stage_thr_id = mining_threads + 3;
  4251. thr = &thr_info[stage_thr_id];
  4252. thr->q = tq_new();
  4253. if (!thr->q)
  4254. quit(1, "Failed to tq_new");
  4255. /* start stage thread */
  4256. if (thr_info_create(thr, NULL, stage_thread, thr))
  4257. quit(1, "stage thread create failed");
  4258. pthread_detach(*thr->pth);
  4259. /* Create a unique get work queue */
  4260. getq = tq_new();
  4261. if (!getq)
  4262. quit(1, "Failed to create getq");
  4263. /* Test each pool to see if we can retrieve and use work and for what
  4264. * it supports */
  4265. for (i = 0; i < total_pools; i++) {
  4266. struct pool *pool;
  4267. pool = pools[i];
  4268. pool->enabled = true;
  4269. if (pool_active(pool, false)) {
  4270. if (!currentpool)
  4271. currentpool = pool;
  4272. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  4273. pools_active++;
  4274. } else {
  4275. if (pool == currentpool)
  4276. currentpool = NULL;
  4277. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  4278. pool->idle = true;
  4279. }
  4280. }
  4281. if (!pools_active) {
  4282. enable_curses();
  4283. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  4284. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  4285. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  4286. for (i = 0; i < total_pools; i++) {
  4287. struct pool *pool;
  4288. pool = pools[i];
  4289. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  4290. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  4291. }
  4292. curses_input("Press enter to exit");
  4293. quit(0, "No servers could be used! Exiting.");
  4294. }
  4295. /* If we want longpoll, enable it for the chosen default pool, or, if
  4296. * the pool does not support longpoll, find the first one that does
  4297. * and use its longpoll support */
  4298. if (want_longpoll) {
  4299. if (currentpool->hdr_path)
  4300. start_longpoll();
  4301. else {
  4302. for (i = 0; i < total_pools; i++) {
  4303. struct pool *pool;
  4304. pool = pools[i];
  4305. if (pool->hdr_path) {
  4306. struct pool *temp = currentpool;
  4307. currentpool = pool;
  4308. start_longpoll();
  4309. /* Not real blocking, but good enough */
  4310. sleep(1);
  4311. currentpool = temp;
  4312. break;
  4313. }
  4314. }
  4315. }
  4316. }
  4317. gettimeofday(&total_tv_start, NULL);
  4318. gettimeofday(&total_tv_end, NULL);
  4319. get_datestamp(datestamp, &total_tv_start);
  4320. #ifdef HAVE_OPENCL
  4321. init_adl(nDevs);
  4322. bool failmessage = false;
  4323. /* start GPU mining threads */
  4324. for (i = 0; i < nDevs * opt_g_threads; i++) {
  4325. int gpu = i % nDevs;
  4326. struct cgpu_info *cgpu;
  4327. struct timeval now;
  4328. gpus[gpu].is_gpu = 1;
  4329. gpus[gpu].cpu_gpu = gpu;
  4330. thr = &thr_info[i];
  4331. thr->id = i;
  4332. cgpu = thr->cgpu = &gpus[gpu];
  4333. thr->q = tq_new();
  4334. if (!thr->q)
  4335. quit(1, "tq_new failed in starting gpu mining threads");
  4336. /* Enable threads for devices set not to mine but disable
  4337. * their queue in case we wish to enable them later*/
  4338. if (gpu_devices[gpu]) {
  4339. if (opt_debug)
  4340. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  4341. tq_push(thr->q, &ping);
  4342. }
  4343. applog(LOG_INFO, "Init GPU thread %i", i);
  4344. clStates[i] = initCl(gpu, name, sizeof(name));
  4345. if (!clStates[i]) {
  4346. enable_curses();
  4347. applog(LOG_ERR, "Failed to init GPU thread %d, disabling device %d", i, gpu);
  4348. if (!failmessage) {
  4349. char *buf;
  4350. applog(LOG_ERR, "The most common reason for this failure is cgminer being unable to read the kernel .cl files");
  4351. applog(LOG_ERR, "You must either CD into the directory you are running cgminer from,");
  4352. applog(LOG_ERR, "or run it from a 'make install'ed location. ");
  4353. applog(LOG_ERR, "Alternatively if it has failed on different GPUs, restarting might help.");
  4354. failmessage = true;
  4355. buf = curses_input("Press enter to continue");
  4356. if (buf)
  4357. free(buf);
  4358. }
  4359. gpu_devices[gpu] = false;
  4360. continue;
  4361. }
  4362. applog(LOG_INFO, "initCl() finished. Found %s", name);
  4363. gettimeofday(&now, NULL);
  4364. get_datestamp(cgpu->init, &now);
  4365. if (unlikely(thr_info_create(thr, NULL, gpuminer_thread, thr)))
  4366. quit(1, "thread %d create failed", i);
  4367. }
  4368. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  4369. #else
  4370. opt_g_threads = 0;
  4371. #endif
  4372. /* start CPU mining threads */
  4373. for (i = gpu_threads; i < mining_threads; i++) {
  4374. int cpu = (i - gpu_threads) % num_processors;
  4375. thr = &thr_info[i];
  4376. thr->id = i;
  4377. cpus[cpu].cpu_gpu = cpu;
  4378. thr->cgpu = &cpus[cpu];
  4379. thr->q = tq_new();
  4380. if (!thr->q)
  4381. quit(1, "tq_new failed in starting cpu mining threads");
  4382. thread_reportin(thr);
  4383. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  4384. quit(1, "thread %d create failed", i);
  4385. }
  4386. applog(LOG_INFO, "%d cpu miner threads started, "
  4387. "using SHA256 '%s' algorithm.",
  4388. opt_n_threads,
  4389. algo_names[opt_algo]);
  4390. if (use_curses)
  4391. enable_curses();
  4392. watchdog_thr_id = mining_threads + 2;
  4393. thr = &thr_info[watchdog_thr_id];
  4394. /* start wakeup thread */
  4395. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  4396. quit(1, "wakeup thread create failed");
  4397. /* Create curses input thread for keyboard input */
  4398. input_thr_id = mining_threads + 4;
  4399. thr = &thr_info[input_thr_id];
  4400. if (thr_info_create(thr, NULL, input_thread, thr))
  4401. quit(1, "input thread create failed");
  4402. pthread_detach(*thr->pth);
  4403. /* Create reinit cpu thread */
  4404. cpur_thr_id = mining_threads + 5;
  4405. thr = &thr_info[cpur_thr_id];
  4406. thr->q = tq_new();
  4407. if (!thr->q)
  4408. quit(1, "tq_new failed for cpur_thr_id");
  4409. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  4410. quit(1, "reinit_cpu thread create failed");
  4411. /* Create reinit gpu thread */
  4412. gpur_thr_id = mining_threads + 6;
  4413. thr = &thr_info[gpur_thr_id];
  4414. thr->q = tq_new();
  4415. if (!thr->q)
  4416. quit(1, "tq_new failed for gpur_thr_id");
  4417. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  4418. quit(1, "reinit_gpu thread create failed");
  4419. /* main loop - simply wait for workio thread to exit */
  4420. pthread_join(*thr_info[work_thr_id].pth, NULL);
  4421. applog(LOG_INFO, "workio thread dead, exiting.");
  4422. gettimeofday(&total_tv_end, NULL);
  4423. disable_curses();
  4424. if (!opt_realquiet && successful_connect)
  4425. print_summary();
  4426. #ifdef HAVE_OPENCL
  4427. clear_adl();
  4428. #endif
  4429. if (gpu_threads)
  4430. free(gpus);
  4431. if (opt_n_threads)
  4432. free(cpus);
  4433. HASH_ITER(hh, staged_work, work, tmpwork) {
  4434. HASH_DEL(staged_work, work);
  4435. free_work(work);
  4436. }
  4437. HASH_ITER(hh, blocks, block, tmpblock) {
  4438. HASH_DEL(blocks, block);
  4439. free(block);
  4440. }
  4441. free(opt_kernel_path);
  4442. curl_global_cleanup();
  4443. return 0;
  4444. }