main.c 126 KB

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