main.c 125 KB

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