main.c 125 KB

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