cgminer.c 114 KB

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