cgminer.c 124 KB

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