cgminer.c 114 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417
  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 (!opt_submit_stale && stale_work(work, true)) {
  1510. applog(LOG_NOTICE, "Stale share detected, discarding");
  1511. total_stale++;
  1512. pool->stale_shares++;
  1513. goto out;
  1514. }
  1515. /* submit solution to bitcoin via JSON-RPC */
  1516. while (!submit_upstream_work(work)) {
  1517. if (!opt_submit_stale && stale_work(work, true)) {
  1518. applog(LOG_NOTICE, "Stale share detected, discarding");
  1519. total_stale++;
  1520. pool->stale_shares++;
  1521. break;
  1522. }
  1523. if (unlikely((opt_retries >= 0) && (++failures > opt_retries))) {
  1524. applog(LOG_ERR, "Failed %d retries ...terminating workio thread", opt_retries);
  1525. kill_work();
  1526. break;
  1527. }
  1528. /* pause, then restart work-request loop */
  1529. applog(LOG_INFO, "json_rpc_call failed on submit_work, retry after %d seconds",
  1530. fail_pause);
  1531. sleep(fail_pause);
  1532. fail_pause += opt_fail_pause;
  1533. }
  1534. fail_pause = opt_fail_pause;
  1535. out:
  1536. workio_cmd_free(wc);
  1537. return NULL;
  1538. }
  1539. static bool workio_submit_work(struct workio_cmd *wc)
  1540. {
  1541. pthread_t submit_thread;
  1542. if (unlikely(pthread_create(&submit_thread, NULL, submit_work_thread, (void *)wc))) {
  1543. applog(LOG_ERR, "Failed to create submit_work_thread");
  1544. return false;
  1545. }
  1546. return true;
  1547. }
  1548. /* Find the pool that currently has the highest priority */
  1549. static struct pool *priority_pool(int choice)
  1550. {
  1551. struct pool *ret = NULL;
  1552. int i;
  1553. for (i = 0; i < total_pools; i++) {
  1554. struct pool *pool = pools[i];
  1555. if (pool->prio == choice) {
  1556. ret = pool;
  1557. break;
  1558. }
  1559. }
  1560. if (unlikely(!ret)) {
  1561. applog(LOG_ERR, "WTF No pool %d found!", choice);
  1562. return pools[choice];
  1563. }
  1564. return ret;
  1565. }
  1566. void switch_pools(struct pool *selected)
  1567. {
  1568. struct pool *pool, *last_pool;
  1569. int i, pool_no;
  1570. mutex_lock(&control_lock);
  1571. last_pool = currentpool;
  1572. pool_no = currentpool->pool_no;
  1573. /* Switch selected to pool number 0 and move the rest down */
  1574. if (selected) {
  1575. if (selected->prio != 0) {
  1576. for (i = 0; i < total_pools; i++) {
  1577. pool = pools[i];
  1578. if (pool->prio < selected->prio)
  1579. pool->prio++;
  1580. }
  1581. selected->prio = 0;
  1582. }
  1583. }
  1584. switch (pool_strategy) {
  1585. /* Both of these set to the master pool */
  1586. case POOL_FAILOVER:
  1587. case POOL_LOADBALANCE:
  1588. for (i = 0; i < total_pools; i++) {
  1589. pool = priority_pool(i);
  1590. if (!pool->idle && pool->enabled) {
  1591. pool_no = pool->pool_no;
  1592. break;
  1593. }
  1594. }
  1595. break;
  1596. /* Both of these simply increment and cycle */
  1597. case POOL_ROUNDROBIN:
  1598. case POOL_ROTATE:
  1599. if (selected) {
  1600. pool_no = selected->pool_no;
  1601. break;
  1602. }
  1603. pool_no++;
  1604. if (pool_no >= total_pools)
  1605. pool_no = 0;
  1606. break;
  1607. default:
  1608. break;
  1609. }
  1610. currentpool = pools[pool_no];
  1611. pool = currentpool;
  1612. mutex_unlock(&control_lock);
  1613. if (pool != last_pool)
  1614. applog(LOG_WARNING, "Switching to %s", pool->rpc_url);
  1615. /* Reset the queued amount to allow more to be queued for the new pool */
  1616. mutex_lock(&qd_lock);
  1617. total_queued = 0;
  1618. mutex_unlock(&qd_lock);
  1619. }
  1620. static void discard_work(struct work *work)
  1621. {
  1622. if (!work->clone && !work->rolls && !work->mined) {
  1623. if (work->pool)
  1624. work->pool->discarded_work++;
  1625. total_discarded++;
  1626. if (opt_debug)
  1627. applog(LOG_DEBUG, "Discarded work");
  1628. } else if (opt_debug)
  1629. applog(LOG_DEBUG, "Discarded cloned or rolled work");
  1630. free_work(work);
  1631. }
  1632. /* This is overkill, but at least we'll know accurately how much work is
  1633. * queued to prevent ever being left without work */
  1634. static void inc_queued(void)
  1635. {
  1636. mutex_lock(&qd_lock);
  1637. total_queued++;
  1638. mutex_unlock(&qd_lock);
  1639. }
  1640. static void dec_queued(void)
  1641. {
  1642. mutex_lock(&qd_lock);
  1643. if (total_queued > 0)
  1644. total_queued--;
  1645. mutex_unlock(&qd_lock);
  1646. }
  1647. static int requests_queued(void)
  1648. {
  1649. int ret;
  1650. mutex_lock(&qd_lock);
  1651. ret = total_queued;
  1652. mutex_unlock(&qd_lock);
  1653. return ret;
  1654. }
  1655. static int discard_stale(void)
  1656. {
  1657. struct work *work, *tmp;
  1658. int i, stale = 0;
  1659. mutex_lock(stgd_lock);
  1660. HASH_ITER(hh, staged_work, work, tmp) {
  1661. if (stale_work(work, false)) {
  1662. HASH_DEL(staged_work, work);
  1663. if (work->clone)
  1664. --staged_clones;
  1665. discard_work(work);
  1666. stale++;
  1667. }
  1668. }
  1669. mutex_unlock(stgd_lock);
  1670. if (opt_debug)
  1671. applog(LOG_DEBUG, "Discarded %d stales that didn't match current hash", stale);
  1672. /* Dec queued outside the loop to not have recursive locks */
  1673. for (i = 0; i < stale; i++)
  1674. dec_queued();
  1675. return stale;
  1676. }
  1677. static bool queue_request(struct thr_info *thr, bool needed);
  1678. static void restart_threads(void)
  1679. {
  1680. int i, stale;
  1681. /* Discard staged work that is now stale */
  1682. stale = discard_stale();
  1683. for (i = 0; i < stale; i++)
  1684. queue_request(NULL, true);
  1685. for (i = 0; i < mining_threads; i++)
  1686. work_restart[i].restart = 1;
  1687. }
  1688. static void set_curblock(char *hexstr, unsigned char *hash)
  1689. {
  1690. unsigned char hash_swap[32];
  1691. char *old_hash = NULL;
  1692. struct timeval tv_now;
  1693. /* Don't free current_hash directly to avoid dereferencing it when
  1694. * we might be accessing its data elsewhere */
  1695. if (current_hash)
  1696. old_hash = current_hash;
  1697. strcpy(current_block, hexstr);
  1698. gettimeofday(&tv_now, NULL);
  1699. get_timestamp(blocktime, &tv_now);
  1700. swap256(hash_swap, hash);
  1701. current_hash = bin2hex(hash_swap, 16);
  1702. if (unlikely(!current_hash))
  1703. quit (1, "set_curblock OOM");
  1704. if (old_hash)
  1705. free(old_hash);
  1706. }
  1707. /* Search to see if this string is from a block that has been seen before */
  1708. static bool block_exists(char *hexstr)
  1709. {
  1710. struct block *s;
  1711. rd_lock(&blk_lock);
  1712. HASH_FIND_STR(blocks, hexstr, s);
  1713. rd_unlock(&blk_lock);
  1714. if (s)
  1715. return true;
  1716. return false;
  1717. }
  1718. /* Tests if this work is from a block that has been seen before */
  1719. static inline bool from_existing_block(struct work *work)
  1720. {
  1721. char *hexstr = bin2hex(work->data, 18);
  1722. bool ret;
  1723. if (unlikely(!hexstr)) {
  1724. applog(LOG_ERR, "from_existing_block OOM");
  1725. return true;
  1726. }
  1727. ret = block_exists(hexstr);
  1728. free(hexstr);
  1729. return ret;
  1730. }
  1731. static void test_work_current(struct work *work, bool longpoll)
  1732. {
  1733. char *hexstr;
  1734. hexstr = bin2hex(work->data, 18);
  1735. if (unlikely(!hexstr)) {
  1736. applog(LOG_ERR, "stage_thread OOM");
  1737. return;
  1738. }
  1739. /* Search to see if this block exists yet and if not, consider it a
  1740. * new block and set the current block details to this one */
  1741. if (!block_exists(hexstr)) {
  1742. struct block *s = calloc(sizeof(struct block), 1);
  1743. if (unlikely(!s))
  1744. quit (1, "test_work_current OOM");
  1745. strcpy(s->hash, hexstr);
  1746. wr_lock(&blk_lock);
  1747. HASH_ADD_STR(blocks, hash, s);
  1748. wr_unlock(&blk_lock);
  1749. set_curblock(hexstr, work->data);
  1750. if (unlikely(++new_blocks == 1))
  1751. goto out_free;
  1752. work_block++;
  1753. if (longpoll)
  1754. applog(LOG_NOTICE, "LONGPOLL detected new block on network, waiting on fresh work");
  1755. else if (have_longpoll)
  1756. applog(LOG_NOTICE, "New block detected on network before longpoll, waiting on fresh work");
  1757. else
  1758. applog(LOG_NOTICE, "New block detected on network, waiting on fresh work");
  1759. restart_threads();
  1760. } else if (longpoll) {
  1761. applog(LOG_NOTICE, "LONGPOLL requested work restart, waiting on fresh work");
  1762. work_block++;
  1763. restart_threads();
  1764. }
  1765. out_free:
  1766. free(hexstr);
  1767. }
  1768. static int tv_sort(struct work *worka, struct work *workb)
  1769. {
  1770. return worka->tv_staged.tv_sec - workb->tv_staged.tv_sec;
  1771. }
  1772. static bool hash_push(struct work *work)
  1773. {
  1774. bool rc = true;
  1775. mutex_lock(stgd_lock);
  1776. if (likely(!getq->frozen)) {
  1777. HASH_ADD_INT(staged_work, id, work);
  1778. HASH_SORT(staged_work, tv_sort);
  1779. if (work->clone)
  1780. ++staged_clones;
  1781. } else
  1782. rc = false;
  1783. pthread_cond_signal(&getq->cond);
  1784. mutex_unlock(stgd_lock);
  1785. return rc;
  1786. }
  1787. static void *stage_thread(void *userdata)
  1788. {
  1789. struct thr_info *mythr = userdata;
  1790. bool ok = true;
  1791. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  1792. while (ok) {
  1793. struct work *work = NULL;
  1794. if (opt_debug)
  1795. applog(LOG_DEBUG, "Popping work to stage thread");
  1796. work = tq_pop(mythr->q, NULL);
  1797. if (unlikely(!work)) {
  1798. applog(LOG_ERR, "Failed to tq_pop in stage_thread");
  1799. ok = false;
  1800. break;
  1801. }
  1802. work->work_block = work_block;
  1803. test_work_current(work, false);
  1804. if (opt_debug)
  1805. applog(LOG_DEBUG, "Pushing work to getwork queue");
  1806. if (unlikely(!hash_push(work))) {
  1807. applog(LOG_WARNING, "Failed to hash_push in stage_thread");
  1808. continue;
  1809. }
  1810. }
  1811. tq_freeze(mythr->q);
  1812. return NULL;
  1813. }
  1814. static bool stage_work(struct work *work)
  1815. {
  1816. if (opt_debug)
  1817. applog(LOG_DEBUG, "Pushing work to stage thread");
  1818. if (unlikely(!tq_push(thr_info[stage_thr_id].q, work))) {
  1819. applog(LOG_ERR, "Could not tq_push work in stage_work");
  1820. return false;
  1821. }
  1822. return true;
  1823. }
  1824. int curses_int(const char *query)
  1825. {
  1826. int ret;
  1827. char *cvar;
  1828. cvar = curses_input(query);
  1829. ret = atoi(cvar);
  1830. free(cvar);
  1831. return ret;
  1832. }
  1833. static bool input_pool(bool live);
  1834. static int active_pools(void)
  1835. {
  1836. int ret = 0;
  1837. int i;
  1838. for (i = 0; i < total_pools; i++) {
  1839. if ((pools[i])->enabled)
  1840. ret++;
  1841. }
  1842. return ret;
  1843. }
  1844. static void display_pool_summary(struct pool *pool)
  1845. {
  1846. double efficiency = 0.0;
  1847. if (curses_active_locked()) {
  1848. wlog("Pool: %s\n", pool->rpc_url);
  1849. wlog("%s long-poll support\n", pool->hdr_path ? "Has" : "Does not have");
  1850. wlog(" Queued work requests: %d\n", pool->getwork_requested);
  1851. wlog(" Share submissions: %d\n", pool->accepted + pool->rejected);
  1852. wlog(" Accepted shares: %d\n", pool->accepted);
  1853. wlog(" Rejected shares: %d\n", pool->rejected);
  1854. if (pool->accepted || pool->rejected)
  1855. wlog(" Reject ratio: %.1f%%\n", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  1856. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  1857. wlog(" Efficiency (accepted / queued): %.0f%%\n", efficiency);
  1858. wlog(" Discarded work due to new blocks: %d\n", pool->discarded_work);
  1859. wlog(" Stale submissions discarded due to new blocks: %d\n", pool->stale_shares);
  1860. wlog(" Unable to get work from server occasions: %d\n", pool->getfail_occasions);
  1861. wlog(" Submitting work remotely delay occasions: %d\n\n", pool->remotefail_occasions);
  1862. wrefresh(logwin);
  1863. unlock_curses();
  1864. }
  1865. }
  1866. /* We can't remove the memory used for this struct pool because there may
  1867. * still be work referencing it. We just remove it from the pools list */
  1868. static void remove_pool(struct pool *pool)
  1869. {
  1870. int i, last_pool = total_pools - 1;
  1871. struct pool *other;
  1872. /* Boost priority of any lower prio than this one */
  1873. for (i = 0; i < total_pools; i++) {
  1874. other = pools[i];
  1875. if (other->prio > pool->prio)
  1876. other->prio--;
  1877. }
  1878. if (pool->pool_no < last_pool) {
  1879. /* Swap the last pool for this one */
  1880. (pools[last_pool])->pool_no = pool->pool_no;
  1881. pools[pool->pool_no] = pools[last_pool];
  1882. }
  1883. /* Give it an invalid number */
  1884. pool->pool_no = total_pools;
  1885. total_pools--;
  1886. }
  1887. void write_config(FILE *fcfg)
  1888. {
  1889. int i;
  1890. /* Write pool values */
  1891. fputs("{\n\"pools\" : [", fcfg);
  1892. for(i = 0; i < total_pools; i++) {
  1893. fprintf(fcfg, "%s\n\t{\n\t\t\"url\" : \"%s\",", i > 0 ? "," : "", pools[i]->rpc_url);
  1894. fprintf(fcfg, "\n\t\t\"user\" : \"%s\",", pools[i]->rpc_user);
  1895. fprintf(fcfg, "\n\t\t\"pass\" : \"%s\"\n\t}", pools[i]->rpc_pass);
  1896. }
  1897. fputs("\n],\n\n", fcfg);
  1898. if (nDevs) {
  1899. /* Write GPU device values */
  1900. fputs("\"intensity\" : \"", fcfg);
  1901. for(i = 0; i < nDevs; i++)
  1902. fprintf(fcfg, gpus[i].dynamic ? "%sd" : "%s%d", i > 0 ? "," : "", gpus[i].intensity);
  1903. #ifdef HAVE_ADL
  1904. fputs("\",\n\"gpu-engine\" : \"", fcfg);
  1905. for(i = 0; i < nDevs; i++)
  1906. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_engine, gpus[i].gpu_engine);
  1907. fputs("\",\n\"gpu-fan\" : \"", fcfg);
  1908. for(i = 0; i < nDevs; i++)
  1909. fprintf(fcfg, "%s%d-%d", i > 0 ? "," : "", gpus[i].min_fan, gpus[i].gpu_fan);
  1910. fputs("\",\n\"gpu-memclock\" : \"", fcfg);
  1911. for(i = 0; i < nDevs; i++)
  1912. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memclock);
  1913. fputs("\",\n\"gpu-memdiff\" : \"", fcfg);
  1914. for(i = 0; i < nDevs; i++)
  1915. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_memdiff);
  1916. fputs("\",\n\"gpu-powertune\" : \"", fcfg);
  1917. for(i = 0; i < nDevs; i++)
  1918. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].gpu_powertune);
  1919. fputs("\",\n\"gpu-vddc\" : \"", fcfg);
  1920. for(i = 0; i < nDevs; i++)
  1921. fprintf(fcfg, "%s%1.3f", i > 0 ? "," : "", gpus[i].gpu_vddc);
  1922. fputs("\",\n\"temp-cutoff\" : \"", fcfg);
  1923. for(i = 0; i < nDevs; i++)
  1924. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.cutofftemp);
  1925. fputs("\",\n\"temp-overheat\" : \"", fcfg);
  1926. for(i = 0; i < nDevs; i++)
  1927. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.overtemp);
  1928. fputs("\",\n\"temp-target\" : \"", fcfg);
  1929. for(i = 0; i < nDevs; i++)
  1930. fprintf(fcfg, "%s%d", i > 0 ? "," : "", gpus[i].adl.targettemp);
  1931. #endif
  1932. fputs("\"", fcfg);
  1933. #ifdef WANT_CPUMINE
  1934. fputs(",\n", fcfg);
  1935. #endif
  1936. }
  1937. #ifdef HAVE_ADL
  1938. if (opt_reorder)
  1939. fprintf(fcfg, ",\n\"gpu-reorder\" : true");
  1940. #endif
  1941. #ifdef WANT_CPUMINE
  1942. fprintf(fcfg, "\n\"algo\" : \"%s\"", algo_names[opt_algo]);
  1943. #endif
  1944. /* Simple bool and int options */
  1945. struct opt_table *opt;
  1946. for (opt = opt_config_table; opt->type != OPT_END; opt++) {
  1947. char *p, *name = strdup(opt->names);
  1948. for (p = strtok(name, "|"); p; p = strtok(NULL, "|")) {
  1949. if (p[1] != '-')
  1950. continue;
  1951. if (opt->type & OPT_NOARG &&
  1952. ((void *)opt->cb == (void *)opt_set_bool || (void *)opt->cb == (void *)opt_set_invbool) &&
  1953. (*(bool *)opt->u.arg == ((void *)opt->cb == (void *)opt_set_bool)))
  1954. fprintf(fcfg, ",\n\"%s\" : true", p+2);
  1955. if (opt->type & OPT_HASARG &&
  1956. ((void *)opt->cb_arg == (void *)set_int_0_to_9999 ||
  1957. (void *)opt->cb_arg == (void *)set_int_1_to_65535 ||
  1958. (void *)opt->cb_arg == (void *)set_int_0_to_10 ||
  1959. (void *)opt->cb_arg == (void *)set_int_1_to_10) && opt->desc != opt_hidden)
  1960. fprintf(fcfg, ",\n\"%s\" : \"%d\"", p+2, *(int *)opt->u.arg);
  1961. }
  1962. }
  1963. /* Special case options */
  1964. fprintf(fcfg, ",\n\"shares\" : \"%d\"", opt_shares);
  1965. if (pool_strategy == POOL_LOADBALANCE)
  1966. fputs(",\n\"load-balance\" : true", fcfg);
  1967. if (pool_strategy == POOL_ROUNDROBIN)
  1968. fputs(",\n\"round-robin\" : true", fcfg);
  1969. if (pool_strategy == POOL_ROTATE)
  1970. fprintf(fcfg, ",\n\"rotate\" : \"%d\"", opt_rotate_period);
  1971. #if defined(unix)
  1972. if (opt_stderr_cmd && *opt_stderr_cmd)
  1973. fprintf(fcfg, ",\n\"monitor\" : \"%s\"", opt_stderr_cmd);
  1974. #endif // defined(unix)
  1975. if (opt_kernel && *opt_kernel)
  1976. fprintf(fcfg, ",\n\"kernel\" : \"%s\"", opt_kernel);
  1977. if (opt_kernel_path && *opt_kernel_path) {
  1978. char *kpath = strdup(opt_kernel_path);
  1979. if (kpath[strlen(kpath)-1] == '/')
  1980. kpath[strlen(kpath)-1] = 0;
  1981. fprintf(fcfg, ",\n\"kernel-path\" : \"%s\"", kpath);
  1982. }
  1983. if (schedstart.enable)
  1984. fprintf(fcfg, ",\n\"sched-time\" : \"%d:%d\"", schedstart.tm.tm_hour, schedstart.tm.tm_min);
  1985. if (schedstop.enable)
  1986. fprintf(fcfg, ",\n\"stop-time\" : \"%d:%d\"", schedstop.tm.tm_hour, schedstop.tm.tm_min);
  1987. if (opt_socks_proxy && *opt_socks_proxy)
  1988. fprintf(fcfg, ",\n\"socks-proxy\" : \"%s\"", opt_socks_proxy);
  1989. for(i = 0; i < nDevs; i++)
  1990. if (!gpus[i].enabled)
  1991. break;
  1992. if (i < nDevs)
  1993. for (i = 0; i < nDevs; i++)
  1994. if (gpus[i].enabled)
  1995. fprintf(fcfg, ",\n\"device\" : \"%d\"", i);
  1996. if (strcmp(opt_api_description, PACKAGE_STRING) != 0)
  1997. fprintf(fcfg, ",\n\"api-description\" : \"%s\"", opt_api_description);
  1998. fputs("\n}", fcfg);
  1999. }
  2000. static void display_pools(void)
  2001. {
  2002. struct pool *pool;
  2003. int selected, i;
  2004. char input;
  2005. opt_loginput = true;
  2006. immedok(logwin, true);
  2007. clear_logwin();
  2008. updated:
  2009. for (i = 0; i < total_pools; i++) {
  2010. pool = pools[i];
  2011. if (pool == current_pool())
  2012. wattron(logwin, A_BOLD);
  2013. if (!pool->enabled)
  2014. wattron(logwin, A_DIM);
  2015. wlogprint("%d: %s %s Priority %d: %s User:%s\n",
  2016. pool->pool_no,
  2017. pool->enabled? "Enabled" : "Disabled",
  2018. pool->idle? "Dead" : "Alive",
  2019. pool->prio,
  2020. pool->rpc_url, pool->rpc_user);
  2021. wattroff(logwin, A_BOLD | A_DIM);
  2022. }
  2023. retry:
  2024. wlogprint("\nCurrent pool management strategy: %s\n",
  2025. strategies[pool_strategy]);
  2026. if (pool_strategy == POOL_ROTATE)
  2027. wlogprint("Set to rotate every %d minutes\n", opt_rotate_period);
  2028. wlogprint("[A]dd pool [R]emove pool [D]isable pool [E]nable pool\n");
  2029. wlogprint("[C]hange management strategy [S]witch pool [I]nformation\n");
  2030. wlogprint("Or press any other key to continue\n");
  2031. input = getch();
  2032. if (!strncasecmp(&input, "a", 1)) {
  2033. input_pool(true);
  2034. goto updated;
  2035. } else if (!strncasecmp(&input, "r", 1)) {
  2036. if (total_pools <= 1) {
  2037. wlogprint("Cannot remove last pool");
  2038. goto retry;
  2039. }
  2040. selected = curses_int("Select pool number");
  2041. if (selected < 0 || selected >= total_pools) {
  2042. wlogprint("Invalid selection\n");
  2043. goto retry;
  2044. }
  2045. pool = pools[selected];
  2046. if (pool == current_pool())
  2047. switch_pools(NULL);
  2048. if (pool == current_pool()) {
  2049. wlogprint("Unable to remove pool due to activity\n");
  2050. goto retry;
  2051. }
  2052. pool->enabled = false;
  2053. remove_pool(pool);
  2054. goto updated;
  2055. } else if (!strncasecmp(&input, "s", 1)) {
  2056. selected = curses_int("Select pool number");
  2057. if (selected < 0 || selected >= total_pools) {
  2058. wlogprint("Invalid selection\n");
  2059. goto retry;
  2060. }
  2061. pool = pools[selected];
  2062. pool->enabled = true;
  2063. switch_pools(pool);
  2064. goto updated;
  2065. } else if (!strncasecmp(&input, "d", 1)) {
  2066. if (active_pools() <= 1) {
  2067. wlogprint("Cannot disable last pool");
  2068. goto retry;
  2069. }
  2070. selected = curses_int("Select pool number");
  2071. if (selected < 0 || selected >= total_pools) {
  2072. wlogprint("Invalid selection\n");
  2073. goto retry;
  2074. }
  2075. pool = pools[selected];
  2076. pool->enabled = false;
  2077. if (pool == current_pool())
  2078. switch_pools(NULL);
  2079. goto updated;
  2080. } else if (!strncasecmp(&input, "e", 1)) {
  2081. selected = curses_int("Select pool number");
  2082. if (selected < 0 || selected >= total_pools) {
  2083. wlogprint("Invalid selection\n");
  2084. goto retry;
  2085. }
  2086. pool = pools[selected];
  2087. pool->enabled = true;
  2088. if (pool->prio < current_pool()->prio)
  2089. switch_pools(pool);
  2090. goto updated;
  2091. } else if (!strncasecmp(&input, "c", 1)) {
  2092. for (i = 0; i <= TOP_STRATEGY; i++)
  2093. wlogprint("%d: %s\n", i, strategies[i]);
  2094. selected = curses_int("Select strategy number type");
  2095. if (selected < 0 || selected > TOP_STRATEGY) {
  2096. wlogprint("Invalid selection\n");
  2097. goto retry;
  2098. }
  2099. if (selected == POOL_ROTATE) {
  2100. opt_rotate_period = curses_int("Select interval in minutes");
  2101. if (opt_rotate_period < 0 || opt_rotate_period > 9999) {
  2102. opt_rotate_period = 0;
  2103. wlogprint("Invalid selection\n");
  2104. goto retry;
  2105. }
  2106. }
  2107. pool_strategy = selected;
  2108. switch_pools(NULL);
  2109. goto updated;
  2110. } else if (!strncasecmp(&input, "i", 1)) {
  2111. selected = curses_int("Select pool number");
  2112. if (selected < 0 || selected >= total_pools) {
  2113. wlogprint("Invalid selection\n");
  2114. goto retry;
  2115. }
  2116. pool = pools[selected];
  2117. display_pool_summary(pool);
  2118. goto retry;
  2119. } else
  2120. clear_logwin();
  2121. immedok(logwin, false);
  2122. opt_loginput = false;
  2123. }
  2124. static void display_options(void)
  2125. {
  2126. int selected;
  2127. char input;
  2128. opt_loginput = true;
  2129. immedok(logwin, true);
  2130. clear_logwin();
  2131. retry:
  2132. wlogprint("[N]ormal [C]lear [S]ilent mode (disable all output)\n");
  2133. 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",
  2134. opt_debug ? "on" : "off",
  2135. want_per_device_stats? "on" : "off",
  2136. opt_quiet ? "on" : "off",
  2137. opt_log_output ? "on" : "off",
  2138. opt_protocol ? "on" : "off",
  2139. opt_log_interval);
  2140. wlogprint("Select an option or any other key to return\n");
  2141. input = getch();
  2142. if (!strncasecmp(&input, "q", 1)) {
  2143. opt_quiet ^= true;
  2144. wlogprint("Quiet mode %s\n", opt_quiet ? "enabled" : "disabled");
  2145. goto retry;
  2146. } else if (!strncasecmp(&input, "v", 1)) {
  2147. opt_log_output ^= true;
  2148. if (opt_log_output)
  2149. opt_quiet = false;
  2150. wlogprint("Verbose mode %s\n", opt_log_output ? "enabled" : "disabled");
  2151. goto retry;
  2152. } else if (!strncasecmp(&input, "n", 1)) {
  2153. opt_log_output = false;
  2154. opt_debug = false;
  2155. opt_quiet = false;
  2156. opt_protocol = false;
  2157. want_per_device_stats = false;
  2158. wlogprint("Output mode reset to normal\n");
  2159. goto retry;
  2160. } else if (!strncasecmp(&input, "d", 1)) {
  2161. opt_debug ^= true;
  2162. opt_log_output = opt_debug;
  2163. if (opt_debug)
  2164. opt_quiet = false;
  2165. wlogprint("Debug mode %s\n", opt_debug ? "enabled" : "disabled");
  2166. goto retry;
  2167. } else if (!strncasecmp(&input, "p", 1)) {
  2168. want_per_device_stats ^= true;
  2169. opt_log_output = want_per_device_stats;
  2170. wlogprint("Per-device stats %s\n", want_per_device_stats ? "enabled" : "disabled");
  2171. goto retry;
  2172. } else if (!strncasecmp(&input, "r", 1)) {
  2173. opt_protocol ^= true;
  2174. if (opt_protocol)
  2175. opt_quiet = false;
  2176. wlogprint("RPC protocol debugging %s\n", opt_protocol ? "enabled" : "disabled");
  2177. goto retry;
  2178. } else if (!strncasecmp(&input, "c", 1))
  2179. clear_logwin();
  2180. else if (!strncasecmp(&input, "l", 1)) {
  2181. selected = curses_int("Interval in seconds");
  2182. if (selected < 0 || selected > 9999) {
  2183. wlogprint("Invalid selection\n");
  2184. goto retry;
  2185. }
  2186. opt_log_interval = selected;
  2187. wlogprint("Log interval set to %d seconds\n", opt_log_interval);
  2188. goto retry;
  2189. } else if (!strncasecmp(&input, "s", 1)) {
  2190. opt_realquiet = true;
  2191. } else
  2192. clear_logwin();
  2193. immedok(logwin, false);
  2194. opt_loginput = false;
  2195. }
  2196. static void start_longpoll(void);
  2197. static void stop_longpoll(void);
  2198. static void set_options(void)
  2199. {
  2200. int selected;
  2201. char input;
  2202. opt_loginput = true;
  2203. immedok(logwin, true);
  2204. clear_logwin();
  2205. retry:
  2206. wlogprint("\n[L]ongpoll: %s\n", want_longpoll ? "On" : "Off");
  2207. 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",
  2208. opt_queue, opt_scantime, opt_expiry, opt_retries, opt_fail_pause);
  2209. wlogprint("Select an option or any other key to return\n");
  2210. input = getch();
  2211. if (!strncasecmp(&input, "q", 1)) {
  2212. selected = curses_int("Extra work items to queue");
  2213. if (selected < 0 || selected > 9999) {
  2214. wlogprint("Invalid selection\n");
  2215. goto retry;
  2216. }
  2217. opt_queue = selected;
  2218. goto retry;
  2219. } else if (!strncasecmp(&input, "l", 1)) {
  2220. want_longpoll ^= true;
  2221. applog(LOG_WARNING, "Longpoll %s", want_longpoll ? "enabled" : "disabled");
  2222. if (!want_longpoll) {
  2223. if (have_longpoll)
  2224. stop_longpoll();
  2225. } else
  2226. start_longpoll();
  2227. goto retry;
  2228. } else if (!strncasecmp(&input, "s", 1)) {
  2229. selected = curses_int("Set scantime in seconds");
  2230. if (selected < 0 || selected > 9999) {
  2231. wlogprint("Invalid selection\n");
  2232. goto retry;
  2233. }
  2234. opt_scantime = selected;
  2235. goto retry;
  2236. } else if (!strncasecmp(&input, "e", 1)) {
  2237. selected = curses_int("Set expiry time in seconds");
  2238. if (selected < 0 || selected > 9999) {
  2239. wlogprint("Invalid selection\n");
  2240. goto retry;
  2241. }
  2242. opt_expiry = selected;
  2243. goto retry;
  2244. } else if (!strncasecmp(&input, "r", 1)) {
  2245. selected = curses_int("Retries before failing (-1 infinite)");
  2246. if (selected < -1 || selected > 9999) {
  2247. wlogprint("Invalid selection\n");
  2248. goto retry;
  2249. }
  2250. opt_retries = selected;
  2251. goto retry;
  2252. } else if (!strncasecmp(&input, "p", 1)) {
  2253. selected = curses_int("Seconds to pause before network retries");
  2254. if (selected < 1 || selected > 9999) {
  2255. wlogprint("Invalid selection\n");
  2256. goto retry;
  2257. }
  2258. opt_fail_pause = selected;
  2259. goto retry;
  2260. } else if (!strncasecmp(&input, "w", 1)) {
  2261. FILE *fcfg;
  2262. char *str, filename[PATH_MAX], prompt[PATH_MAX + 50];
  2263. #if defined(unix)
  2264. strcpy(filename, getenv("HOME"));
  2265. if (*filename)
  2266. strcat(filename, "/");
  2267. else
  2268. strcpy(filename, "");
  2269. strcat(filename, ".cgminer/");
  2270. mkdir(filename, 0777);
  2271. #else
  2272. strcpy(filename, "");
  2273. #endif
  2274. strcat(filename, def_conf);
  2275. sprintf(prompt, "Config filename to write (Enter for default) [%s]", filename);
  2276. str = curses_input(prompt);
  2277. if (strcmp(str, "-1")) {
  2278. struct stat statbuf;
  2279. strcpy(filename, str);
  2280. if (!stat(filename, &statbuf)) {
  2281. wlogprint("File exists, overwrite?\n");
  2282. input = getch();
  2283. if (strncasecmp(&input, "y", 1))
  2284. goto retry;
  2285. }
  2286. }
  2287. fcfg = fopen(filename, "w");
  2288. if (!fcfg) {
  2289. wlogprint("Cannot open or create file\n");
  2290. goto retry;
  2291. }
  2292. write_config(fcfg);
  2293. fclose(fcfg);
  2294. goto retry;
  2295. } else
  2296. clear_logwin();
  2297. immedok(logwin, false);
  2298. opt_loginput = false;
  2299. }
  2300. static void *input_thread(void __maybe_unused *userdata)
  2301. {
  2302. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2303. if (!curses_active)
  2304. return NULL;
  2305. while (1) {
  2306. char input;
  2307. input = getch();
  2308. if (!strncasecmp(&input, "q", 1)) {
  2309. kill_work();
  2310. return NULL;
  2311. } else if (!strncasecmp(&input, "d", 1))
  2312. display_options();
  2313. else if (!strncasecmp(&input, "p", 1))
  2314. display_pools();
  2315. else if (!strncasecmp(&input, "s", 1))
  2316. set_options();
  2317. else if (have_opencl && !strncasecmp(&input, "g", 1))
  2318. manage_gpu();
  2319. if (opt_realquiet) {
  2320. disable_curses();
  2321. break;
  2322. }
  2323. }
  2324. return NULL;
  2325. }
  2326. static void *workio_thread(void *userdata)
  2327. {
  2328. struct thr_info *mythr = userdata;
  2329. bool ok = true;
  2330. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2331. while (ok) {
  2332. struct workio_cmd *wc;
  2333. if (opt_debug)
  2334. applog(LOG_DEBUG, "Popping work to work thread");
  2335. /* wait for workio_cmd sent to us, on our queue */
  2336. wc = tq_pop(mythr->q, NULL);
  2337. if (unlikely(!wc)) {
  2338. applog(LOG_ERR, "Failed to tq_pop in workio_thread");
  2339. ok = false;
  2340. break;
  2341. }
  2342. /* process workio_cmd */
  2343. switch (wc->cmd) {
  2344. case WC_GET_WORK:
  2345. ok = workio_get_work(wc);
  2346. break;
  2347. case WC_SUBMIT_WORK:
  2348. ok = workio_submit_work(wc);
  2349. break;
  2350. default:
  2351. ok = false;
  2352. break;
  2353. }
  2354. }
  2355. tq_freeze(mythr->q);
  2356. return NULL;
  2357. }
  2358. static void *api_thread(void *userdata)
  2359. {
  2360. struct thr_info *mythr = userdata;
  2361. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2362. api();
  2363. PTH(mythr) = 0L;
  2364. return NULL;
  2365. }
  2366. void thread_reportin(struct thr_info *thr)
  2367. {
  2368. gettimeofday(&thr->last, NULL);
  2369. thr->cgpu->status = LIFE_WELL;
  2370. thr->getwork = false;
  2371. }
  2372. static inline void thread_reportout(struct thr_info *thr)
  2373. {
  2374. thr->getwork = true;
  2375. }
  2376. static void hashmeter(int thr_id, struct timeval *diff,
  2377. unsigned long hashes_done)
  2378. {
  2379. struct timeval temp_tv_end, total_diff;
  2380. double secs;
  2381. double local_secs;
  2382. double utility, efficiency = 0.0;
  2383. static double local_mhashes_done = 0;
  2384. static double rolling = 0;
  2385. double local_mhashes = (double)hashes_done / 1000000.0;
  2386. bool showlog = false;
  2387. /* Update the last time this thread reported in */
  2388. if (thr_id >= 0)
  2389. gettimeofday(&thr_info[thr_id].last, NULL);
  2390. /* Don't bother calculating anything if we're not displaying it */
  2391. if (opt_realquiet || !opt_log_interval)
  2392. return;
  2393. secs = (double)diff->tv_sec + ((double)diff->tv_usec / 1000000.0);
  2394. /* So we can call hashmeter from a non worker thread */
  2395. if (thr_id >= 0) {
  2396. struct thr_info *thr = &thr_info[thr_id];
  2397. struct cgpu_info *cgpu = thr_info[thr_id].cgpu;
  2398. double thread_rolling = 0.0;
  2399. int i;
  2400. if (opt_debug)
  2401. applog(LOG_DEBUG, "[thread %d: %lu hashes, %.0f khash/sec]",
  2402. thr_id, hashes_done, hashes_done / secs);
  2403. /* Rolling average for each thread and each device */
  2404. decay_time(&thr->rolling, local_mhashes / secs);
  2405. for (i = 0; i < mining_threads; i++) {
  2406. struct thr_info *th = &thr_info[i];
  2407. if (th->cgpu == cgpu)
  2408. thread_rolling += th->rolling;
  2409. }
  2410. decay_time(&cgpu->rolling, thread_rolling);
  2411. cgpu->total_mhashes += local_mhashes;
  2412. // If needed, output detailed, per-device stats
  2413. if (want_per_device_stats) {
  2414. struct timeval now;
  2415. struct timeval elapsed;
  2416. gettimeofday(&now, NULL);
  2417. timeval_subtract(&elapsed, &now, &thr->cgpu->last_message_tv);
  2418. if (opt_log_interval <= elapsed.tv_sec) {
  2419. struct cgpu_info *cgpu = thr->cgpu;
  2420. char logline[255];
  2421. cgpu->last_message_tv = now;
  2422. get_statline(logline, cgpu);
  2423. if (!curses_active) {
  2424. printf("%s \r", logline);
  2425. fflush(stdout);
  2426. } else
  2427. applog(LOG_INFO, "%s", logline);
  2428. }
  2429. }
  2430. }
  2431. /* Totals are updated by all threads so can race without locking */
  2432. mutex_lock(&hash_lock);
  2433. gettimeofday(&temp_tv_end, NULL);
  2434. timeval_subtract(&total_diff, &temp_tv_end, &total_tv_end);
  2435. total_mhashes_done += local_mhashes;
  2436. local_mhashes_done += local_mhashes;
  2437. if (total_diff.tv_sec < opt_log_interval)
  2438. /* Only update the total every opt_log_interval seconds */
  2439. goto out_unlock;
  2440. showlog = true;
  2441. gettimeofday(&total_tv_end, NULL);
  2442. local_secs = (double)total_diff.tv_sec + ((double)total_diff.tv_usec / 1000000.0);
  2443. decay_time(&rolling, local_mhashes_done / local_secs);
  2444. timeval_subtract(&total_diff, &total_tv_end, &total_tv_start);
  2445. total_secs = (double)total_diff.tv_sec +
  2446. ((double)total_diff.tv_usec / 1000000.0);
  2447. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  2448. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  2449. sprintf(statusline, "%s(%ds):%.1f (avg):%.1f Mh/s | Q:%d A:%d R:%d HW:%d E:%.0f%% U:%.2f/m",
  2450. want_per_device_stats ? "ALL " : "",
  2451. opt_log_interval, rolling, total_mhashes_done / total_secs,
  2452. total_getworks, total_accepted, total_rejected, hw_errors, efficiency, utility);
  2453. local_mhashes_done = 0;
  2454. out_unlock:
  2455. mutex_unlock(&hash_lock);
  2456. if (showlog) {
  2457. if (!curses_active) {
  2458. printf("%s \r", statusline);
  2459. fflush(stdout);
  2460. } else
  2461. applog(LOG_INFO, "%s", statusline);
  2462. }
  2463. }
  2464. static bool pool_active(struct pool *pool, bool pinging)
  2465. {
  2466. bool ret = false;
  2467. json_t *val;
  2468. CURL *curl;
  2469. bool rolltime;
  2470. curl = curl_easy_init();
  2471. if (unlikely(!curl)) {
  2472. applog(LOG_ERR, "CURL initialisation failed");
  2473. return false;
  2474. }
  2475. applog(LOG_INFO, "Testing pool %s", pool->rpc_url);
  2476. val = json_rpc_call(curl, pool->rpc_url, pool->rpc_userpass, rpc_req,
  2477. true, false, &rolltime, pool, false);
  2478. if (val) {
  2479. struct work *work = make_work();
  2480. bool rc;
  2481. rc = work_decode(json_object_get(val, "result"), work);
  2482. if (rc) {
  2483. applog(LOG_DEBUG, "Successfully retrieved and deciphered work from pool %u %s",
  2484. pool->pool_no, pool->rpc_url);
  2485. work->pool = pool;
  2486. work->rolltime = rolltime;
  2487. if (opt_debug)
  2488. applog(LOG_DEBUG, "Pushing pooltest work to base pool");
  2489. tq_push(thr_info[stage_thr_id].q, work);
  2490. total_getworks++;
  2491. pool->getwork_requested++;
  2492. inc_queued();
  2493. ret = true;
  2494. gettimeofday(&pool->tv_idle, NULL);
  2495. } else {
  2496. applog(LOG_DEBUG, "Successfully retrieved but FAILED to decipher work from pool %u %s",
  2497. pool->pool_no, pool->rpc_url);
  2498. free_work(work);
  2499. }
  2500. json_decref(val);
  2501. } else {
  2502. applog(LOG_DEBUG, "FAILED to retrieve work from pool %u %s",
  2503. pool->pool_no, pool->rpc_url);
  2504. if (!pinging)
  2505. applog(LOG_WARNING, "Pool %u slow/down or URL or credentials invalid", pool->pool_no);
  2506. }
  2507. curl_easy_cleanup(curl);
  2508. return ret;
  2509. }
  2510. static void pool_died(struct pool *pool)
  2511. {
  2512. if (!pool_tset(pool, &pool->idle)) {
  2513. applog(LOG_WARNING, "Pool %d %s not responding!", pool->pool_no, pool->rpc_url);
  2514. gettimeofday(&pool->tv_idle, NULL);
  2515. switch_pools(NULL);
  2516. }
  2517. }
  2518. static inline int cp_prio(void)
  2519. {
  2520. int prio;
  2521. mutex_lock(&control_lock);
  2522. prio = currentpool->prio;
  2523. mutex_unlock(&control_lock);
  2524. return prio;
  2525. }
  2526. static void pool_resus(struct pool *pool)
  2527. {
  2528. applog(LOG_WARNING, "Pool %d %s recovered", pool->pool_no, pool->rpc_url);
  2529. if (pool->prio < cp_prio() && pool_strategy == POOL_FAILOVER)
  2530. switch_pools(NULL);
  2531. }
  2532. static bool queue_request(struct thr_info *thr, bool needed)
  2533. {
  2534. struct workio_cmd *wc;
  2535. int rq = requests_queued();
  2536. if (rq >= mining_threads + staged_clones)
  2537. return true;
  2538. /* fill out work request message */
  2539. wc = calloc(1, sizeof(*wc));
  2540. if (unlikely(!wc)) {
  2541. applog(LOG_ERR, "Failed to calloc wc in queue_request");
  2542. return false;
  2543. }
  2544. wc->cmd = WC_GET_WORK;
  2545. if (thr)
  2546. wc->thr = thr;
  2547. else
  2548. wc->thr = NULL;
  2549. /* If we're queueing work faster than we can stage it, consider the
  2550. * system lagging and allow work to be gathered from another pool if
  2551. * possible */
  2552. if (rq && needed && !requests_staged() && !opt_fail_only)
  2553. wc->lagging = true;
  2554. if (opt_debug)
  2555. applog(LOG_DEBUG, "Queueing getwork request to work thread");
  2556. /* send work request to workio thread */
  2557. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2558. applog(LOG_ERR, "Failed to tq_push in queue_request");
  2559. workio_cmd_free(wc);
  2560. return false;
  2561. }
  2562. inc_queued();
  2563. return true;
  2564. }
  2565. static struct work *hash_pop(const struct timespec *abstime)
  2566. {
  2567. struct work *work = NULL;
  2568. int rc = 0;
  2569. mutex_lock(stgd_lock);
  2570. while (!getq->frozen && !HASH_COUNT(staged_work) && !rc)
  2571. rc = pthread_cond_timedwait(&getq->cond, stgd_lock, abstime);
  2572. if (HASH_COUNT(staged_work)) {
  2573. work = staged_work;
  2574. HASH_DEL(staged_work, work);
  2575. if (work->clone)
  2576. --staged_clones;
  2577. }
  2578. mutex_unlock(stgd_lock);
  2579. return work;
  2580. }
  2581. static inline bool should_roll(struct work *work)
  2582. {
  2583. if (work->pool == current_pool() || pool_strategy == POOL_LOADBALANCE)
  2584. return true;
  2585. return false;
  2586. }
  2587. static inline bool can_roll(struct work *work)
  2588. {
  2589. return (work->pool && !stale_work(work, false) && work->rolltime &&
  2590. work->rolls < 11 && !work->clone);
  2591. }
  2592. static void roll_work(struct work *work)
  2593. {
  2594. uint32_t *work_ntime;
  2595. uint32_t ntime;
  2596. work_ntime = (uint32_t *)(work->data + 68);
  2597. ntime = be32toh(*work_ntime);
  2598. ntime++;
  2599. *work_ntime = htobe32(ntime);
  2600. local_work++;
  2601. work->rolls++;
  2602. work->blk.nonce = 0;
  2603. if (opt_debug)
  2604. applog(LOG_DEBUG, "Successfully rolled work");
  2605. /* This is now a different work item so it needs a different ID for the
  2606. * hashtable */
  2607. work->id = inc_totalwork();
  2608. }
  2609. static bool reuse_work(struct work *work)
  2610. {
  2611. if (can_roll(work) && should_roll(work)) {
  2612. roll_work(work);
  2613. return true;
  2614. }
  2615. return false;
  2616. }
  2617. static void roll_cloned(struct work *work)
  2618. {
  2619. struct work *work_clone = make_work();
  2620. memcpy(work_clone, work, sizeof(struct work));
  2621. while (reuse_work(work)) {
  2622. work_clone->clone = true;
  2623. if (opt_debug)
  2624. applog(LOG_DEBUG, "Pushing rolled cloned work to stage thread");
  2625. if (unlikely(!stage_work(work_clone)))
  2626. break;
  2627. work_clone = make_work();
  2628. memcpy(work_clone, work, sizeof(struct work));
  2629. }
  2630. free_work(work_clone);
  2631. }
  2632. static struct work *get_work(bool requested, struct thr_info *thr, const int thr_id)
  2633. {
  2634. struct timespec abstime = {0, 0};
  2635. struct work *work = NULL;
  2636. bool newreq = false;
  2637. struct timeval now;
  2638. struct pool *pool;
  2639. /* Tell the watchdog thread this thread is waiting on getwork and
  2640. * should not be restarted */
  2641. thread_reportout(thr);
  2642. while (!work) {
  2643. pool = current_pool();
  2644. if (!requested || requests_queued() < opt_queue) {
  2645. if (unlikely(!queue_request(thr, true)))
  2646. quit(1, "Failed to queue_request in get_work");
  2647. newreq = true;
  2648. }
  2649. if (requested && !newreq && !requests_staged() && requests_queued() >= mining_threads &&
  2650. !pool_tset(pool, &pool->lagging)) {
  2651. applog(LOG_WARNING, "Pool %d not providing work fast enough", pool->pool_no);
  2652. pool->getfail_occasions++;
  2653. total_go++;
  2654. }
  2655. newreq = requested = false;
  2656. gettimeofday(&now, NULL);
  2657. abstime.tv_sec = now.tv_sec + 60;
  2658. if (opt_debug)
  2659. applog(LOG_DEBUG, "Popping work from get queue to get work");
  2660. /* wait for 1st response, or get cached response */
  2661. work = hash_pop(&abstime);
  2662. if (unlikely(!work)) {
  2663. /* Attempt to switch pools if this one times out */
  2664. pool_died(pool);
  2665. } else if (stale_work(work, false)) {
  2666. dec_queued();
  2667. discard_work(work);
  2668. }
  2669. }
  2670. pool = work->pool;
  2671. /* If we make it here we have succeeded in getting fresh work */
  2672. if (likely(pool)) {
  2673. pool_tclear(pool, &pool->lagging);
  2674. if (pool_tclear(pool, &pool->idle))
  2675. pool_resus(pool);
  2676. }
  2677. roll_cloned(work);
  2678. dec_queued();
  2679. work->thr_id = thr_id;
  2680. work->mined = true;
  2681. thread_reportin(thr);
  2682. return work;
  2683. }
  2684. bool submit_work_sync(struct thr_info *thr, const struct work *work_in)
  2685. {
  2686. struct workio_cmd *wc;
  2687. /* fill out work request message */
  2688. wc = calloc(1, sizeof(*wc));
  2689. if (unlikely(!wc)) {
  2690. applog(LOG_ERR, "Failed to calloc wc in submit_work_sync");
  2691. return false;
  2692. }
  2693. wc->u.work = make_work();
  2694. wc->cmd = WC_SUBMIT_WORK;
  2695. wc->thr = thr;
  2696. memcpy(wc->u.work, work_in, sizeof(*work_in));
  2697. if (opt_debug)
  2698. applog(LOG_DEBUG, "Pushing submit work to work thread");
  2699. /* send solution to workio thread */
  2700. if (unlikely(!tq_push(thr_info[work_thr_id].q, wc))) {
  2701. applog(LOG_ERR, "Failed to tq_push work in submit_work_sync");
  2702. goto err_out;
  2703. }
  2704. return true;
  2705. err_out:
  2706. workio_cmd_free(wc);
  2707. return false;
  2708. }
  2709. bool hashtest(const struct work *work)
  2710. {
  2711. uint32_t *data32 = (uint32_t *)(work->data);
  2712. unsigned char swap[128];
  2713. uint32_t *swap32 = (uint32_t *)swap;
  2714. unsigned char hash1[32];
  2715. unsigned char hash2[32];
  2716. uint32_t *hash2_32 = (uint32_t *)hash2;
  2717. int i;
  2718. for (i = 0; i < 80 / 4; i++)
  2719. swap32[i] = swab32(data32[i]);
  2720. sha2(swap, 80, hash1, false);
  2721. sha2(hash1, 32, hash2, false);
  2722. for (i = 0; i < 32 / 4; i++)
  2723. hash2_32[i] = swab32(hash2_32[i]);
  2724. memcpy((void*)work->hash, hash2, 32);
  2725. return fulltest(work->hash, work->target);
  2726. }
  2727. bool submit_nonce(struct thr_info *thr, struct work *work, uint32_t nonce)
  2728. {
  2729. work->data[64 + 12 + 0] = (nonce >> 0) & 0xff;
  2730. work->data[64 + 12 + 1] = (nonce >> 8) & 0xff;
  2731. work->data[64 + 12 + 2] = (nonce >> 16) & 0xff;
  2732. work->data[64 + 12 + 3] = (nonce >> 24) & 0xff;
  2733. /* Do one last check before attempting to submit the work */
  2734. if (!hashtest(work)) {
  2735. applog(LOG_INFO, "Share below target");
  2736. return true;
  2737. }
  2738. return submit_work_sync(thr, work);
  2739. }
  2740. static inline bool abandon_work(struct work *work, struct timeval *wdiff, uint64_t hashes)
  2741. {
  2742. if (wdiff->tv_sec > opt_scantime ||
  2743. work->blk.nonce >= MAXTHREADS - hashes ||
  2744. hashes >= 0xfffffffe ||
  2745. stale_work(work, false))
  2746. return true;
  2747. return false;
  2748. }
  2749. void *miner_thread(void *userdata)
  2750. {
  2751. struct thr_info *mythr = userdata;
  2752. const int thr_id = mythr->id;
  2753. struct cgpu_info *cgpu = mythr->cgpu;
  2754. struct device_api *api = cgpu->api;
  2755. /* Try to cycle approximately 5 times before each log update */
  2756. const unsigned long def_cycle = opt_log_interval / 5 ? : 1;
  2757. unsigned long cycle;
  2758. struct timeval tv_start, tv_end, tv_workstart, tv_lastupdate;
  2759. struct timeval diff, sdiff, wdiff;
  2760. uint32_t max_nonce = api->can_limit_work ? api->can_limit_work(mythr) : 0xffffffff;
  2761. uint32_t hashes_done = 0;
  2762. uint32_t hashes;
  2763. struct work *work = make_work();
  2764. unsigned const int request_interval = opt_scantime * 2 / 3 ? : 1;
  2765. unsigned const long request_nonce = MAXTHREADS / 3 * 2;
  2766. bool requested = false;
  2767. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2768. if (api->thread_init && !api->thread_init(mythr))
  2769. goto out;
  2770. if (opt_debug)
  2771. applog(LOG_DEBUG, "Popping ping in miner thread");
  2772. tq_pop(mythr->q, NULL); /* Wait for a ping to start */
  2773. sdiff.tv_sec = sdiff.tv_usec = 0;
  2774. gettimeofday(&tv_lastupdate, NULL);
  2775. while (1) {
  2776. work_restart[thr_id].restart = 0;
  2777. if (api->free_work && likely(work->pool))
  2778. api->free_work(mythr, work);
  2779. free_work(work);
  2780. work = get_work(requested, mythr, thr_id);
  2781. requested = false;
  2782. cycle = (can_roll(work) && should_roll(work)) ? 1 : def_cycle;
  2783. gettimeofday(&tv_workstart, NULL);
  2784. work->blk.nonce = 0;
  2785. if (api->prepare_work && !api->prepare_work(mythr, work)) {
  2786. applog(LOG_ERR, "work prepare failed, exiting "
  2787. "mining thread %d", thr_id);
  2788. break;
  2789. }
  2790. do {
  2791. gettimeofday(&tv_start, NULL);
  2792. hashes = api->scanhash(mythr, work, work->blk.nonce + max_nonce);
  2793. if (unlikely(work_restart[thr_id].restart)) {
  2794. /* Apart from device_thread 0, we stagger the
  2795. * starting of every next thread to try and get
  2796. * all devices busy before worrying about
  2797. * getting work for their extra threads */
  2798. if (mythr->device_thread) {
  2799. struct timespec rgtp;
  2800. rgtp.tv_sec = 0;
  2801. rgtp.tv_nsec = 250 * mythr->device_thread * 1000000;
  2802. nanosleep(&rgtp, NULL);
  2803. }
  2804. break;
  2805. }
  2806. if (unlikely(!hashes))
  2807. goto out;
  2808. hashes_done += hashes;
  2809. gettimeofday(&tv_end, NULL);
  2810. timeval_subtract(&diff, &tv_end, &tv_start);
  2811. sdiff.tv_sec += diff.tv_sec;
  2812. sdiff.tv_usec += diff.tv_usec;
  2813. if (sdiff.tv_usec > 1000000) {
  2814. ++sdiff.tv_sec;
  2815. sdiff.tv_usec -= 1000000;
  2816. }
  2817. timeval_subtract(&wdiff, &tv_end, &tv_workstart);
  2818. if (!requested) {
  2819. if (wdiff.tv_sec > request_interval || work->blk.nonce > request_nonce) {
  2820. thread_reportout(mythr);
  2821. if (unlikely(!queue_request(mythr, false))) {
  2822. applog(LOG_ERR, "Failed to queue_request in miner_thread %d", thr_id);
  2823. goto out;
  2824. }
  2825. thread_reportin(mythr);
  2826. requested = true;
  2827. }
  2828. }
  2829. if (unlikely(sdiff.tv_sec < cycle)) {
  2830. if (likely(!api->can_limit_work || max_nonce == 0xffffffff))
  2831. continue;
  2832. {
  2833. int mult = 1000000 / ((sdiff.tv_usec + 0x400) / 0x400) + 0x10;
  2834. mult *= cycle;
  2835. if (max_nonce > (0xffffffff * 0x400) / mult)
  2836. max_nonce = 0xffffffff;
  2837. else
  2838. max_nonce = (max_nonce * mult) / 0x400;
  2839. }
  2840. } else if (unlikely(sdiff.tv_sec > cycle) && api->can_limit_work) {
  2841. max_nonce = max_nonce * cycle / sdiff.tv_sec;
  2842. } else if (unlikely(sdiff.tv_usec > 100000) && api->can_limit_work) {
  2843. max_nonce = max_nonce * 0x400 / (((cycle * 1000000) + sdiff.tv_usec) / (cycle * 1000000 / 0x400));
  2844. }
  2845. timeval_subtract(&diff, &tv_end, &tv_lastupdate);
  2846. if (diff.tv_sec >= opt_log_interval) {
  2847. hashmeter(thr_id, &diff, hashes_done);
  2848. hashes_done = 0;
  2849. tv_lastupdate = tv_end;
  2850. }
  2851. if (unlikely(mythr->pause || !cgpu->enabled)) {
  2852. applog(LOG_WARNING, "Thread %d being disabled", thr_id);
  2853. mythr->rolling = mythr->cgpu->rolling = 0;
  2854. if (opt_debug)
  2855. applog(LOG_DEBUG, "Popping wakeup ping in miner thread");
  2856. thread_reportout(mythr);
  2857. tq_pop(mythr->q, NULL); /* Ignore ping that's popped */
  2858. thread_reportin(mythr);
  2859. applog(LOG_WARNING, "Thread %d being re-enabled", thr_id);
  2860. }
  2861. sdiff.tv_sec = sdiff.tv_usec = 0;
  2862. } while (!abandon_work(work, &wdiff, hashes));
  2863. }
  2864. out:
  2865. if (api->thread_shutdown)
  2866. api->thread_shutdown(mythr);
  2867. thread_reportin(mythr);
  2868. applog(LOG_ERR, "Thread %d failure, exiting", thr_id);
  2869. tq_freeze(mythr->q);
  2870. return NULL;
  2871. }
  2872. enum {
  2873. STAT_SLEEP_INTERVAL = 1,
  2874. STAT_CTR_INTERVAL = 10000000,
  2875. FAILURE_INTERVAL = 30,
  2876. };
  2877. /* Stage another work item from the work returned in a longpoll */
  2878. static void convert_to_work(json_t *val, bool rolltime, struct pool *pool)
  2879. {
  2880. struct work *work;
  2881. bool rc;
  2882. work = make_work();
  2883. rc= work_decode(json_object_get(val, "result"), work);
  2884. if (unlikely(!rc)) {
  2885. applog(LOG_ERR, "Could not convert longpoll data to work");
  2886. return;
  2887. }
  2888. work->pool = pool;
  2889. work->rolltime = rolltime;
  2890. /* We'll be checking this work item twice, but we already know it's
  2891. * from a new block so explicitly force the new block detection now
  2892. * rather than waiting for it to hit the stage thread. This also
  2893. * allows testwork to know whether LP discovered the block or not. */
  2894. test_work_current(work, true);
  2895. roll_cloned(work);
  2896. if (opt_debug)
  2897. applog(LOG_DEBUG, "Pushing converted work to stage thread");
  2898. if (unlikely(!stage_work(work)))
  2899. free_work(work);
  2900. else if (opt_debug)
  2901. applog(LOG_DEBUG, "Converted longpoll data to work");
  2902. }
  2903. /* If we want longpoll, enable it for the chosen default pool, or, if
  2904. * the pool does not support longpoll, find the first one that does
  2905. * and use its longpoll support */
  2906. static struct pool *select_longpoll_pool(void)
  2907. {
  2908. struct pool *cp = current_pool();
  2909. int i;
  2910. if (cp->hdr_path)
  2911. return cp;
  2912. for (i = 0; i < total_pools; i++) {
  2913. struct pool *pool = pools[i];
  2914. if (pool->hdr_path)
  2915. return pool;
  2916. }
  2917. return NULL;
  2918. }
  2919. static void *longpoll_thread(void *userdata)
  2920. {
  2921. char *copy_start, *hdr_path, *lp_url = NULL;
  2922. struct thr_info *mythr = userdata;
  2923. struct timeval start, end;
  2924. bool need_slash = false;
  2925. struct pool *sp, *pool;
  2926. CURL *curl = NULL;
  2927. int failures = 0;
  2928. bool rolltime;
  2929. json_t *val;
  2930. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  2931. pthread_detach(pthread_self());
  2932. curl = curl_easy_init();
  2933. if (unlikely(!curl)) {
  2934. applog(LOG_ERR, "CURL initialisation failed");
  2935. goto out;
  2936. }
  2937. tq_pop(mythr->q, NULL);
  2938. pool = select_longpoll_pool();
  2939. new_longpoll:
  2940. if (!pool) {
  2941. applog(LOG_WARNING, "No long-poll found on any pool server");
  2942. goto out;
  2943. }
  2944. hdr_path = pool->hdr_path;
  2945. /* full URL */
  2946. if (strstr(hdr_path, "://")) {
  2947. lp_url = hdr_path;
  2948. hdr_path = NULL;
  2949. } else {
  2950. /* absolute path, on current server */
  2951. copy_start = (*hdr_path == '/') ? (hdr_path + 1) : hdr_path;
  2952. if (pool->rpc_url[strlen(pool->rpc_url) - 1] != '/')
  2953. need_slash = true;
  2954. lp_url = malloc(strlen(pool->rpc_url) + strlen(copy_start) + 2);
  2955. if (!lp_url)
  2956. goto out;
  2957. sprintf(lp_url, "%s%s%s", pool->rpc_url, need_slash ? "/" : "", copy_start);
  2958. }
  2959. have_longpoll = true;
  2960. applog(LOG_WARNING, "Long-polling activated for %s", lp_url);
  2961. while (1) {
  2962. gettimeofday(&start, NULL);
  2963. val = json_rpc_call(curl, lp_url, pool->rpc_userpass, rpc_req,
  2964. false, true, &rolltime, pool, false);
  2965. if (likely(val)) {
  2966. convert_to_work(val, rolltime, pool);
  2967. failures = 0;
  2968. json_decref(val);
  2969. } else {
  2970. /* Some pools regularly drop the longpoll request so
  2971. * only see this as longpoll failure if it happens
  2972. * immediately and just restart it the rest of the
  2973. * time. */
  2974. gettimeofday(&end, NULL);
  2975. if (end.tv_sec - start.tv_sec > 30)
  2976. continue;
  2977. if (opt_retries == -1 || failures++ < opt_retries) {
  2978. applog(LOG_WARNING,
  2979. "longpoll failed for %s, sleeping for 30s", lp_url);
  2980. sleep(30);
  2981. } else {
  2982. applog(LOG_ERR,
  2983. "longpoll failed for %s, ending thread", lp_url);
  2984. goto out;
  2985. }
  2986. }
  2987. sp = select_longpoll_pool();
  2988. if (sp != pool) {
  2989. if (likely(lp_url))
  2990. free(lp_url);
  2991. pool = sp;
  2992. goto new_longpoll;
  2993. }
  2994. }
  2995. out:
  2996. if (curl)
  2997. curl_easy_cleanup(curl);
  2998. tq_freeze(mythr->q);
  2999. return NULL;
  3000. }
  3001. static void stop_longpoll(void)
  3002. {
  3003. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3004. thr_info_cancel(thr);
  3005. have_longpoll = false;
  3006. tq_freeze(thr->q);
  3007. }
  3008. static void start_longpoll(void)
  3009. {
  3010. struct thr_info *thr = &thr_info[longpoll_thr_id];
  3011. tq_thaw(thr->q);
  3012. if (unlikely(thr_info_create(thr, NULL, longpoll_thread, thr)))
  3013. quit(1, "longpoll thread create failed");
  3014. if (opt_debug)
  3015. applog(LOG_DEBUG, "Pushing ping to longpoll thread");
  3016. tq_push(thr_info[longpoll_thr_id].q, &ping);
  3017. }
  3018. void reinit_device(struct cgpu_info *cgpu)
  3019. {
  3020. if (cgpu->api->reinit_device)
  3021. cgpu->api->reinit_device(cgpu);
  3022. }
  3023. /* Makes sure the hashmeter keeps going even if mining threads stall, updates
  3024. * the screen at regular intervals, and restarts threads if they appear to have
  3025. * died. */
  3026. static void *watchdog_thread(void __maybe_unused *userdata)
  3027. {
  3028. const unsigned int interval = 3;
  3029. static struct timeval rotate_tv;
  3030. struct timeval zero_tv;
  3031. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  3032. memset(&zero_tv, 0, sizeof(struct timeval));
  3033. gettimeofday(&rotate_tv, NULL);
  3034. while (1) {
  3035. int i;
  3036. struct timeval now;
  3037. sleep(interval);
  3038. if (requests_queued() < opt_queue)
  3039. queue_request(NULL, false);
  3040. hashmeter(-1, &zero_tv, 0);
  3041. if (curses_active_locked()) {
  3042. change_logwinsize();
  3043. curses_print_status();
  3044. for (i = 0; i < mining_threads; i++)
  3045. curses_print_devstatus(i);
  3046. clearok(statuswin, true);
  3047. doupdate();
  3048. unlock_curses();
  3049. }
  3050. gettimeofday(&now, NULL);
  3051. for (i = 0; i < total_pools; i++) {
  3052. struct pool *pool = pools[i];
  3053. if (!pool->enabled)
  3054. continue;
  3055. /* Test pool is idle once every minute */
  3056. if (pool->idle && now.tv_sec - pool->tv_idle.tv_sec > 60) {
  3057. gettimeofday(&pool->tv_idle, NULL);
  3058. if (pool_active(pool, true) && pool_tclear(pool, &pool->idle))
  3059. pool_resus(pool);
  3060. }
  3061. }
  3062. if (pool_strategy == POOL_ROTATE && now.tv_sec - rotate_tv.tv_sec > 60 * opt_rotate_period) {
  3063. gettimeofday(&rotate_tv, NULL);
  3064. switch_pools(NULL);
  3065. }
  3066. if (!sched_paused && !should_run()) {
  3067. applog(LOG_WARNING, "Pausing execution as per stop time %02d:%02d scheduled",
  3068. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3069. if (!schedstart.enable) {
  3070. quit(0, "Terminating execution as planned");
  3071. break;
  3072. }
  3073. applog(LOG_WARNING, "Will restart execution as scheduled at %02d:%02d",
  3074. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3075. sched_paused = true;
  3076. for (i = 0; i < mining_threads; i++) {
  3077. struct thr_info *thr;
  3078. thr = &thr_info[i];
  3079. thr->pause = true;
  3080. }
  3081. } else if (sched_paused && should_run()) {
  3082. applog(LOG_WARNING, "Restarting execution as per start time %02d:%02d scheduled",
  3083. schedstart.tm.tm_hour, schedstart.tm.tm_min);
  3084. if (schedstop.enable)
  3085. applog(LOG_WARNING, "Will pause execution as scheduled at %02d:%02d",
  3086. schedstop.tm.tm_hour, schedstop.tm.tm_min);
  3087. sched_paused = false;
  3088. for (i = 0; i < mining_threads; i++) {
  3089. struct thr_info *thr;
  3090. thr = &thr_info[i];
  3091. /* Don't touch disabled devices */
  3092. if (!thr->cgpu->enabled)
  3093. continue;
  3094. thr->pause = false;
  3095. tq_push(thr->q, &ping);
  3096. }
  3097. }
  3098. #ifdef HAVE_OPENCL
  3099. for (i = 0; i < total_devices; ++i) {
  3100. struct cgpu_info *cgpu = devices[i];
  3101. struct thr_info *thr = cgpu->thread;
  3102. bool *enable;
  3103. int gpu;
  3104. if (cgpu->api != &opencl_api)
  3105. continue;
  3106. /* Use only one thread per device to determine if the GPU is healthy */
  3107. if (i >= nDevs)
  3108. break;
  3109. gpu = thr->cgpu->device_id;
  3110. enable = &cgpu->enabled;
  3111. #ifdef HAVE_ADL
  3112. if (adl_active && gpus[gpu].has_adl)
  3113. gpu_autotune(gpu, enable);
  3114. if (opt_debug && gpus[gpu].has_adl) {
  3115. int engineclock = 0, memclock = 0, activity = 0, fanspeed = 0, fanpercent = 0, powertune = 0;
  3116. float temp = 0, vddc = 0;
  3117. if (gpu_stats(gpu, &temp, &engineclock, &memclock, &vddc, &activity, &fanspeed, &fanpercent, &powertune))
  3118. applog(LOG_DEBUG, "%.1f C F: %d%%(%dRPM) E: %dMHz M: %dMhz V: %.3fV A: %d%% P: %d%%",
  3119. temp, fanpercent, fanspeed, engineclock, memclock, vddc, activity, powertune);
  3120. }
  3121. #endif
  3122. /* Thread is waiting on getwork or disabled */
  3123. if (thr->getwork || !*enable)
  3124. continue;
  3125. if (gpus[gpu].status != LIFE_WELL && now.tv_sec - thr->last.tv_sec < 60) {
  3126. applog(LOG_ERR, "Device %d recovered, GPU %d declared WELL!", i, gpu);
  3127. gpus[gpu].status = LIFE_WELL;
  3128. } else if (now.tv_sec - thr->last.tv_sec > 60 && gpus[gpu].status == LIFE_WELL) {
  3129. thr->rolling = thr->cgpu->rolling = 0;
  3130. gpus[gpu].status = LIFE_SICK;
  3131. applog(LOG_ERR, "Device %d idle for more than 60 seconds, GPU %d declared SICK!", i, gpu);
  3132. gettimeofday(&thr->sick, NULL);
  3133. #ifdef HAVE_ADL
  3134. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3135. applog(LOG_ERR, "GPU still showing activity suggesting a hard hang.");
  3136. applog(LOG_ERR, "Will not attempt to auto-restart it.");
  3137. } else
  3138. #endif
  3139. if (opt_restart) {
  3140. applog(LOG_ERR, "Attempting to restart GPU");
  3141. reinit_device(thr->cgpu);
  3142. }
  3143. } else if (now.tv_sec - thr->last.tv_sec > 600 && gpus[i].status == LIFE_SICK) {
  3144. gpus[gpu].status = LIFE_DEAD;
  3145. applog(LOG_ERR, "Device %d not responding for more than 10 minutes, GPU %d declared DEAD!", i, gpu);
  3146. gettimeofday(&thr->sick, NULL);
  3147. } else if (now.tv_sec - thr->sick.tv_sec > 60 &&
  3148. (gpus[i].status == LIFE_SICK || gpus[i].status == LIFE_DEAD)) {
  3149. /* Attempt to restart a GPU that's sick or dead once every minute */
  3150. gettimeofday(&thr->sick, NULL);
  3151. #ifdef HAVE_ADL
  3152. if (adl_active && gpus[gpu].has_adl && gpu_activity(gpu) > 50) {
  3153. /* Again do not attempt to restart a device that may have hard hung */
  3154. } else
  3155. #endif
  3156. if (opt_restart)
  3157. reinit_device(thr->cgpu);
  3158. }
  3159. }
  3160. #endif
  3161. }
  3162. return NULL;
  3163. }
  3164. static void log_print_status(struct cgpu_info *cgpu)
  3165. {
  3166. char logline[255];
  3167. get_statline(logline, cgpu);
  3168. applog(LOG_WARNING, "%s", logline);
  3169. }
  3170. static void print_summary(void)
  3171. {
  3172. struct timeval diff;
  3173. int hours, mins, secs, i;
  3174. double utility, efficiency = 0.0;
  3175. timeval_subtract(&diff, &total_tv_end, &total_tv_start);
  3176. hours = diff.tv_sec / 3600;
  3177. mins = (diff.tv_sec % 3600) / 60;
  3178. secs = diff.tv_sec % 60;
  3179. utility = total_accepted / ( total_secs ? total_secs : 1 ) * 60;
  3180. efficiency = total_getworks ? total_accepted * 100.0 / total_getworks : 0.0;
  3181. applog(LOG_WARNING, "\nSummary of runtime statistics:\n");
  3182. applog(LOG_WARNING, "Started at %s", datestamp);
  3183. if (total_pools == 1)
  3184. applog(LOG_WARNING, "Pool: %s", pools[0]->rpc_url);
  3185. #ifdef WANT_CPUMINE
  3186. if (opt_n_threads)
  3187. applog(LOG_WARNING, "CPU hasher algorithm used: %s", algo_names[opt_algo]);
  3188. #endif
  3189. applog(LOG_WARNING, "Runtime: %d hrs : %d mins : %d secs", hours, mins, secs);
  3190. if (total_secs)
  3191. applog(LOG_WARNING, "Average hashrate: %.1f Megahash/s", total_mhashes_done / total_secs);
  3192. applog(LOG_WARNING, "Solved blocks: %d", found_blocks);
  3193. applog(LOG_WARNING, "Queued work requests: %d", total_getworks);
  3194. applog(LOG_WARNING, "Share submissions: %d", total_accepted + total_rejected);
  3195. applog(LOG_WARNING, "Accepted shares: %d", total_accepted);
  3196. applog(LOG_WARNING, "Rejected shares: %d", total_rejected);
  3197. if (total_accepted || total_rejected)
  3198. applog(LOG_WARNING, "Reject ratio: %.1f%%", (double)(total_rejected * 100) / (double)(total_accepted + total_rejected));
  3199. applog(LOG_WARNING, "Hardware errors: %d", hw_errors);
  3200. applog(LOG_WARNING, "Efficiency (accepted / queued): %.0f%%", efficiency);
  3201. applog(LOG_WARNING, "Utility (accepted shares / min): %.2f/min\n", utility);
  3202. applog(LOG_WARNING, "Discarded work due to new blocks: %d", total_discarded);
  3203. applog(LOG_WARNING, "Stale submissions discarded due to new blocks: %d", total_stale);
  3204. applog(LOG_WARNING, "Unable to get work from server occasions: %d", total_go);
  3205. applog(LOG_WARNING, "Work items generated locally: %d", local_work);
  3206. applog(LOG_WARNING, "Submitting work remotely delay occasions: %d", total_ro);
  3207. applog(LOG_WARNING, "New blocks detected on network: %d\n", new_blocks);
  3208. if (total_pools > 1) {
  3209. for (i = 0; i < total_pools; i++) {
  3210. struct pool *pool = pools[i];
  3211. applog(LOG_WARNING, "Pool: %s", pool->rpc_url);
  3212. applog(LOG_WARNING, " Queued work requests: %d", pool->getwork_requested);
  3213. applog(LOG_WARNING, " Share submissions: %d", pool->accepted + pool->rejected);
  3214. applog(LOG_WARNING, " Accepted shares: %d", pool->accepted);
  3215. applog(LOG_WARNING, " Rejected shares: %d", pool->rejected);
  3216. if (pool->accepted || pool->rejected)
  3217. applog(LOG_WARNING, " Reject ratio: %.1f%%", (double)(pool->rejected * 100) / (double)(pool->accepted + pool->rejected));
  3218. efficiency = pool->getwork_requested ? pool->accepted * 100.0 / pool->getwork_requested : 0.0;
  3219. applog(LOG_WARNING, " Efficiency (accepted / queued): %.0f%%", efficiency);
  3220. applog(LOG_WARNING, " Discarded work due to new blocks: %d", pool->discarded_work);
  3221. applog(LOG_WARNING, " Stale submissions discarded due to new blocks: %d", pool->stale_shares);
  3222. applog(LOG_WARNING, " Unable to get work from server occasions: %d", pool->getfail_occasions);
  3223. applog(LOG_WARNING, " Submitting work remotely delay occasions: %d\n", pool->remotefail_occasions);
  3224. }
  3225. }
  3226. applog(LOG_WARNING, "Summary of per device statistics:\n");
  3227. for (i = 0; i < total_devices; ++i) {
  3228. if (devices[i]->enabled)
  3229. log_print_status(devices[i]);
  3230. }
  3231. if (opt_shares)
  3232. applog(LOG_WARNING, "Mined %d accepted shares of %d requested\n", total_accepted, opt_shares);
  3233. fflush(stdout);
  3234. fflush(stderr);
  3235. if (opt_shares > total_accepted)
  3236. quit(1, "Did not successfully mine as many shares as were requested.");
  3237. }
  3238. void quit(int status, const char *format, ...)
  3239. {
  3240. va_list ap;
  3241. disable_curses();
  3242. if (!opt_realquiet && successful_connect)
  3243. print_summary();
  3244. if (format) {
  3245. va_start(ap, format);
  3246. vfprintf(stderr, format, ap);
  3247. va_end(ap);
  3248. }
  3249. fprintf(stderr, "\n");
  3250. fflush(stderr);
  3251. exit(status);
  3252. }
  3253. char *curses_input(const char *query)
  3254. {
  3255. char *input;
  3256. echo();
  3257. input = malloc(255);
  3258. if (!input)
  3259. quit(1, "Failed to malloc input");
  3260. leaveok(logwin, false);
  3261. wlogprint("%s:\n", query);
  3262. wgetnstr(logwin, input, 255);
  3263. if (!strlen(input))
  3264. strcpy(input, "-1");
  3265. leaveok(logwin, true);
  3266. noecho();
  3267. return input;
  3268. }
  3269. static bool input_pool(bool live)
  3270. {
  3271. char *url = NULL, *user = NULL, *pass = NULL;
  3272. struct pool *pool = NULL;
  3273. bool ret = false;
  3274. immedok(logwin, true);
  3275. if (total_pools == MAX_POOLS) {
  3276. wlogprint("Reached maximum number of pools.\n");
  3277. goto out;
  3278. }
  3279. wlogprint("Input server details.\n");
  3280. url = curses_input("URL");
  3281. if (!url)
  3282. goto out;
  3283. if (strncmp(url, "http://", 7) &&
  3284. strncmp(url, "https://", 8)) {
  3285. char *httpinput;
  3286. httpinput = malloc(255);
  3287. if (!httpinput)
  3288. quit(1, "Failed to malloc httpinput");
  3289. strcpy(httpinput, "http://");
  3290. strncat(httpinput, url, 248);
  3291. free(url);
  3292. url = httpinput;
  3293. }
  3294. user = curses_input("Username");
  3295. if (!user)
  3296. goto out;
  3297. pass = curses_input("Password");
  3298. if (!pass)
  3299. goto out;
  3300. pool = calloc(sizeof(struct pool), 1);
  3301. if (!pool)
  3302. quit(1, "Failed to realloc pools in input_pool");
  3303. pool->pool_no = total_pools;
  3304. pool->prio = total_pools;
  3305. if (unlikely(pthread_mutex_init(&pool->pool_lock, NULL)))
  3306. quit (1, "Failed to pthread_mutex_init in input_pool");
  3307. pool->rpc_url = url;
  3308. pool->rpc_user = user;
  3309. pool->rpc_pass = pass;
  3310. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3311. if (!pool->rpc_userpass)
  3312. quit(1, "Failed to malloc userpass");
  3313. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3314. pool->tv_idle.tv_sec = ~0UL;
  3315. /* Test the pool is not idle if we're live running, otherwise
  3316. * it will be tested separately */
  3317. ret = true;
  3318. pool->enabled = true;
  3319. if (live && !pool_active(pool, false))
  3320. pool->idle = true;
  3321. pools[total_pools++] = pool;
  3322. out:
  3323. immedok(logwin, false);
  3324. if (!ret) {
  3325. if (url)
  3326. free(url);
  3327. if (user)
  3328. free(user);
  3329. if (pass)
  3330. free(pass);
  3331. if (pool)
  3332. free(pool);
  3333. }
  3334. return ret;
  3335. }
  3336. #if defined(unix)
  3337. static void fork_monitor()
  3338. {
  3339. // Make a pipe: [readFD, writeFD]
  3340. int pfd[2];
  3341. int r = pipe(pfd);
  3342. if (r<0) {
  3343. perror("pipe - failed to create pipe for --monitor");
  3344. exit(1);
  3345. }
  3346. // Make stderr write end of pipe
  3347. fflush(stderr);
  3348. r = dup2(pfd[1], 2);
  3349. if (r<0) {
  3350. perror("dup2 - failed to alias stderr to write end of pipe for --monitor");
  3351. exit(1);
  3352. }
  3353. r = close(pfd[1]);
  3354. if (r<0) {
  3355. perror("close - failed to close write end of pipe for --monitor");
  3356. exit(1);
  3357. }
  3358. // Don't allow a dying monitor to kill the main process
  3359. sighandler_t sr0 = signal(SIGPIPE, SIG_IGN);
  3360. sighandler_t sr1 = signal(SIGPIPE, SIG_IGN);
  3361. if (SIG_ERR==sr0 || SIG_ERR==sr1) {
  3362. perror("signal - failed to edit signal mask for --monitor");
  3363. exit(1);
  3364. }
  3365. // Fork a child process
  3366. r = fork();
  3367. if (r<0) {
  3368. perror("fork - failed to fork child process for --monitor");
  3369. exit(1);
  3370. }
  3371. // Child: launch monitor command
  3372. if (0==r) {
  3373. // Make stdin read end of pipe
  3374. r = dup2(pfd[0], 0);
  3375. if (r<0) {
  3376. perror("dup2 - in child, failed to alias read end of pipe to stdin for --monitor");
  3377. exit(1);
  3378. }
  3379. close(pfd[0]);
  3380. if (r<0) {
  3381. perror("close - in child, failed to close read end of pipe for --monitor");
  3382. exit(1);
  3383. }
  3384. // Launch user specified command
  3385. execl("/bin/bash", "/bin/bash", "-c", opt_stderr_cmd, (char*)NULL);
  3386. perror("execl - in child failed to exec user specified command for --monitor");
  3387. exit(1);
  3388. }
  3389. // Parent: clean up unused fds and bail
  3390. r = close(pfd[0]);
  3391. if (r<0) {
  3392. perror("close - failed to close read end of pipe for --monitor");
  3393. exit(1);
  3394. }
  3395. }
  3396. #endif // defined(unix)
  3397. void enable_curses(void) {
  3398. int x,y;
  3399. lock_curses();
  3400. if (curses_active) {
  3401. unlock_curses();
  3402. return;
  3403. }
  3404. mainwin = initscr();
  3405. getmaxyx(mainwin, y, x);
  3406. statuswin = newwin(logstart, x, 0, 0);
  3407. leaveok(statuswin, true);
  3408. logwin = newwin(y - logcursor, 0, logcursor, 0);
  3409. idlok(logwin, true);
  3410. scrollok(logwin, true);
  3411. leaveok(logwin, true);
  3412. cbreak();
  3413. noecho();
  3414. curses_active = true;
  3415. unlock_curses();
  3416. }
  3417. /* TODO: fix need a dummy CPU device_api even if no support for CPU mining */
  3418. #ifndef WANT_CPUMINE
  3419. struct device_api cpu_api;
  3420. struct device_api cpu_api = {
  3421. .name = "CPU",
  3422. };
  3423. #endif
  3424. #ifdef USE_BITFORCE
  3425. extern struct device_api bitforce_api;
  3426. #endif
  3427. static int cgminer_id_count = 0;
  3428. void enable_device(struct cgpu_info *cgpu)
  3429. {
  3430. cgpu->enabled = true;
  3431. devices[cgpu->cgminer_id = cgminer_id_count++] = cgpu;
  3432. mining_threads += cgpu->threads;
  3433. #ifdef HAVE_OPENCL
  3434. if (cgpu->api == &opencl_api) {
  3435. gpu_threads += cgpu->threads;
  3436. }
  3437. #endif
  3438. }
  3439. int main (int argc, char *argv[])
  3440. {
  3441. unsigned int i, pools_active = 0;
  3442. unsigned int j, k;
  3443. struct block *block, *tmpblock;
  3444. struct work *work, *tmpwork;
  3445. struct sigaction handler;
  3446. struct thr_info *thr;
  3447. /* This dangerous functions tramples random dynamically allocated
  3448. * variables so do it before anything at all */
  3449. if (unlikely(curl_global_init(CURL_GLOBAL_ALL)))
  3450. quit(1, "Failed to curl_global_init");
  3451. mutex_init(&hash_lock);
  3452. mutex_init(&qd_lock);
  3453. mutex_init(&curses_lock);
  3454. mutex_init(&control_lock);
  3455. rwlock_init(&blk_lock);
  3456. rwlock_init(&netacc_lock);
  3457. sprintf(packagename, "%s %s", PACKAGE, VERSION);
  3458. #ifdef WANT_CPUMINE
  3459. init_max_name_len();
  3460. #endif
  3461. handler.sa_handler = &sighandler;
  3462. handler.sa_flags = 0;
  3463. sigemptyset(&handler.sa_mask);
  3464. sigaction(SIGTERM, &handler, &termhandler);
  3465. sigaction(SIGINT, &handler, &inthandler);
  3466. opt_kernel_path = alloca(PATH_MAX);
  3467. strcpy(opt_kernel_path, CGMINER_PREFIX);
  3468. cgminer_path = alloca(PATH_MAX);
  3469. strcpy(cgminer_path, dirname(argv[0]));
  3470. strcat(cgminer_path, "/");
  3471. #ifdef WANT_CPUMINE
  3472. // Hack to make cgminer silent when called recursively on WIN32
  3473. int skip_to_bench = 0;
  3474. #if defined(WIN32)
  3475. char buf[32];
  3476. if (GetEnvironmentVariable("CGMINER_BENCH_ALGO", buf, 16))
  3477. skip_to_bench = 1;
  3478. #endif // defined(WIN32)
  3479. #endif
  3480. block = calloc(sizeof(struct block), 1);
  3481. if (unlikely(!block))
  3482. quit (1, "main OOM");
  3483. for (i = 0; i < 36; i++)
  3484. strcat(block->hash, "0");
  3485. HASH_ADD_STR(blocks, hash, block);
  3486. strcpy(current_block, block->hash);
  3487. INIT_LIST_HEAD(&scan_devices);
  3488. memset(gpus, 0, sizeof(gpus));
  3489. for (i = 0; i < MAX_GPUDEVICES; i++)
  3490. gpus[i].dynamic = true;
  3491. memset(devices, 0, sizeof(devices));
  3492. /* parse command line */
  3493. opt_register_table(opt_config_table,
  3494. "Options for both config file and command line");
  3495. opt_register_table(opt_cmdline_table,
  3496. "Options for command line only");
  3497. if (!config_loaded)
  3498. load_default_config();
  3499. opt_parse(&argc, argv, applog_and_exit);
  3500. if (argc != 1)
  3501. quit(1, "Unexpected extra commandline arguments");
  3502. applog(LOG_WARNING, "Started %s", packagename);
  3503. strcat(opt_kernel_path, "/");
  3504. if (want_per_device_stats)
  3505. opt_log_output = true;
  3506. #ifdef WANT_CPUMINE
  3507. if (0<=opt_bench_algo) {
  3508. double rate = bench_algo_stage3(opt_bench_algo);
  3509. if (!skip_to_bench) {
  3510. printf("%.5f (%s)\n", rate, algo_names[opt_bench_algo]);
  3511. } else {
  3512. // Write result to shared memory for parent
  3513. #if defined(WIN32)
  3514. char unique_name[64];
  3515. if (GetEnvironmentVariable("CGMINER_SHARED_MEM", unique_name, 32)) {
  3516. HANDLE map_handle = CreateFileMapping(
  3517. INVALID_HANDLE_VALUE, // use paging file
  3518. NULL, // default security attributes
  3519. PAGE_READWRITE, // read/write access
  3520. 0, // size: high 32-bits
  3521. 4096, // size: low 32-bits
  3522. unique_name // name of map object
  3523. );
  3524. if (NULL!=map_handle) {
  3525. void *shared_mem = MapViewOfFile(
  3526. map_handle, // object to map view of
  3527. FILE_MAP_WRITE, // read/write access
  3528. 0, // high offset: map from
  3529. 0, // low offset: beginning
  3530. 0 // default: map entire file
  3531. );
  3532. if (NULL!=shared_mem)
  3533. CopyMemory(shared_mem, &rate, sizeof(rate));
  3534. (void)UnmapViewOfFile(shared_mem);
  3535. }
  3536. (void)CloseHandle(map_handle);
  3537. }
  3538. #endif
  3539. }
  3540. exit(0);
  3541. }
  3542. #endif
  3543. #ifdef HAVE_OPENCL
  3544. if (!opt_nogpu)
  3545. opencl_api.api_detect();
  3546. #endif
  3547. #ifdef USE_BITFORCE
  3548. bitforce_api.api_detect();
  3549. #endif
  3550. #ifdef WANT_CPUMINE
  3551. cpu_api.api_detect();
  3552. #endif
  3553. if (devices_enabled == -1) {
  3554. applog(LOG_ERR, "Devices detected:");
  3555. for (i = 0; i < total_devices; ++i) {
  3556. applog(LOG_ERR, " %2d. %s%d", i, devices[i]->api->name, devices[i]->device_id);
  3557. }
  3558. quit(0, "%d devices listed", total_devices);
  3559. }
  3560. mining_threads = 0;
  3561. gpu_threads = 0;
  3562. if (devices_enabled) {
  3563. for (i = 0; i < (sizeof(devices_enabled) * 8) - 1; ++i) {
  3564. if (devices_enabled & (1 << i)) {
  3565. if (i >= total_devices)
  3566. quit (1, "Command line options set a device that doesn't exist");
  3567. enable_device(devices[i]);
  3568. } else if (i < total_devices) {
  3569. if (opt_removedisabled) {
  3570. if (devices[i]->api == &cpu_api)
  3571. --opt_n_threads;
  3572. } else {
  3573. enable_device(devices[i]);
  3574. }
  3575. devices[i]->enabled = false;
  3576. }
  3577. }
  3578. total_devices = cgminer_id_count;
  3579. } else {
  3580. for (i = 0; i < total_devices; ++i)
  3581. enable_device(devices[i]);
  3582. }
  3583. if (!total_devices)
  3584. quit(1, "All devices disabled, cannot mine!");
  3585. devcursor = 8;
  3586. logstart = devcursor + total_devices + 1;
  3587. logcursor = logstart + 1;
  3588. if (opt_realquiet)
  3589. use_curses = false;
  3590. if (!total_pools) {
  3591. if (use_curses)
  3592. enable_curses();
  3593. applog(LOG_WARNING, "Need to specify at least one pool server.");
  3594. if (!use_curses || (use_curses && !input_pool(false)))
  3595. quit(1, "Pool setup failed");
  3596. }
  3597. for (i = 0; i < total_pools; i++) {
  3598. struct pool *pool = pools[i];
  3599. if (!pool->rpc_userpass) {
  3600. if (!pool->rpc_user || !pool->rpc_pass)
  3601. quit(1, "No login credentials supplied for pool %u %s", i, pool->rpc_url);
  3602. pool->rpc_userpass = malloc(strlen(pool->rpc_user) + strlen(pool->rpc_pass) + 2);
  3603. if (!pool->rpc_userpass)
  3604. quit(1, "Failed to malloc userpass");
  3605. sprintf(pool->rpc_userpass, "%s:%s", pool->rpc_user, pool->rpc_pass);
  3606. } else {
  3607. pool->rpc_user = malloc(strlen(pool->rpc_userpass) + 1);
  3608. if (!pool->rpc_user)
  3609. quit(1, "Failed to malloc user");
  3610. strcpy(pool->rpc_user, pool->rpc_userpass);
  3611. pool->rpc_user = strtok(pool->rpc_user, ":");
  3612. if (!pool->rpc_user)
  3613. quit(1, "Failed to find colon delimiter in userpass");
  3614. }
  3615. }
  3616. /* Set the currentpool to pool 0 */
  3617. currentpool = pools[0];
  3618. #ifdef HAVE_SYSLOG_H
  3619. if (use_syslog)
  3620. openlog(PACKAGE, LOG_PID, LOG_USER);
  3621. #endif
  3622. #if defined(unix)
  3623. if (opt_stderr_cmd)
  3624. fork_monitor();
  3625. #endif // defined(unix)
  3626. total_threads = mining_threads + 8;
  3627. work_restart = calloc(total_threads, sizeof(*work_restart));
  3628. if (!work_restart)
  3629. quit(1, "Failed to calloc work_restart");
  3630. thr_info = calloc(total_threads, sizeof(*thr));
  3631. if (!thr_info)
  3632. quit(1, "Failed to calloc thr_info");
  3633. /* init workio thread info */
  3634. work_thr_id = mining_threads;
  3635. thr = &thr_info[work_thr_id];
  3636. thr->id = work_thr_id;
  3637. thr->q = tq_new();
  3638. if (!thr->q)
  3639. quit(1, "Failed to tq_new");
  3640. /* start work I/O thread */
  3641. if (thr_info_create(thr, NULL, workio_thread, thr))
  3642. quit(1, "workio thread create failed");
  3643. /* init longpoll thread info */
  3644. longpoll_thr_id = mining_threads + 1;
  3645. thr = &thr_info[longpoll_thr_id];
  3646. thr->id = longpoll_thr_id;
  3647. thr->q = tq_new();
  3648. if (!thr->q)
  3649. quit(1, "Failed to tq_new");
  3650. stage_thr_id = mining_threads + 3;
  3651. thr = &thr_info[stage_thr_id];
  3652. thr->q = tq_new();
  3653. if (!thr->q)
  3654. quit(1, "Failed to tq_new");
  3655. /* start stage thread */
  3656. if (thr_info_create(thr, NULL, stage_thread, thr))
  3657. quit(1, "stage thread create failed");
  3658. pthread_detach(thr->pth);
  3659. /* Create a unique get work queue */
  3660. getq = tq_new();
  3661. if (!getq)
  3662. quit(1, "Failed to create getq");
  3663. /* We use the getq mutex as the staged lock */
  3664. stgd_lock = &getq->mutex;
  3665. retry_pools:
  3666. /* Test each pool to see if we can retrieve and use work and for what
  3667. * it supports */
  3668. for (i = 0; i < total_pools; i++) {
  3669. struct pool *pool;
  3670. pool = pools[i];
  3671. pool->enabled = true;
  3672. if (pool_active(pool, false)) {
  3673. if (!currentpool)
  3674. currentpool = pool;
  3675. applog(LOG_INFO, "Pool %d %s active", pool->pool_no, pool->rpc_url);
  3676. pools_active++;
  3677. } else {
  3678. if (pool == currentpool)
  3679. currentpool = NULL;
  3680. applog(LOG_WARNING, "Unable to get work from pool %d %s", pool->pool_no, pool->rpc_url);
  3681. pool->idle = true;
  3682. }
  3683. }
  3684. if (!pools_active) {
  3685. if (use_curses)
  3686. enable_curses();
  3687. applog(LOG_ERR, "No servers were found that could be used to get work from.");
  3688. applog(LOG_ERR, "Please check the details from the list below of the servers you have input");
  3689. applog(LOG_ERR, "Most likely you have input the wrong URL, forgotten to add a port, or have not set up workers");
  3690. for (i = 0; i < total_pools; i++) {
  3691. struct pool *pool;
  3692. pool = pools[i];
  3693. applog(LOG_WARNING, "Pool: %d URL: %s User: %s Password: %s",
  3694. i, pool->rpc_url, pool->rpc_user, pool->rpc_pass);
  3695. }
  3696. if (use_curses) {
  3697. halfdelay(150);
  3698. applog(LOG_ERR, "Press any key to exit, or cgminer will try again in 15s.");
  3699. if (getch() != ERR)
  3700. quit(0, "No servers could be used! Exiting.");
  3701. nocbreak();
  3702. } else
  3703. quit(0, "No servers could be used! Exiting.");
  3704. goto retry_pools;
  3705. }
  3706. if (want_longpoll)
  3707. start_longpoll();
  3708. gettimeofday(&total_tv_start, NULL);
  3709. gettimeofday(&total_tv_end, NULL);
  3710. get_datestamp(datestamp, &total_tv_start);
  3711. #ifndef HAVE_OPENCL
  3712. opt_g_threads = 0;
  3713. #endif
  3714. // Start threads
  3715. k = 0;
  3716. for (i = 0; i < total_devices; ++i) {
  3717. struct cgpu_info *cgpu = devices[i];
  3718. for (j = 0; j < cgpu->threads; ++j, ++k) {
  3719. thr = &thr_info[k];
  3720. thr->id = k;
  3721. thr->cgpu = cgpu;
  3722. thr->device_thread = j;
  3723. thr->q = tq_new();
  3724. if (!thr->q)
  3725. quit(1, "tq_new failed in starting %s%d mining thread (#%d)", cgpu->api->name, cgpu->device_id, i);
  3726. /* Enable threads for devices set not to mine but disable
  3727. * their queue in case we wish to enable them later */
  3728. if (cgpu->enabled) {
  3729. if (opt_debug)
  3730. applog(LOG_DEBUG, "Pushing ping to thread %d", thr->id);
  3731. tq_push(thr->q, &ping);
  3732. }
  3733. if (cgpu->api->thread_prepare && !cgpu->api->thread_prepare(thr))
  3734. continue;
  3735. if (unlikely(thr_info_create(thr, NULL, miner_thread, thr)))
  3736. quit(1, "thread %d create failed", thr->id);
  3737. cgpu->thread = thr;
  3738. }
  3739. }
  3740. #ifdef HAVE_OPENCL
  3741. applog(LOG_INFO, "%d gpu miner threads started", gpu_threads);
  3742. for (i = 0; i < nDevs; i++)
  3743. pause_dynamic_threads(i);
  3744. #endif
  3745. #ifdef WANT_CPUMINE
  3746. applog(LOG_INFO, "%d cpu miner threads started, "
  3747. "using SHA256 '%s' algorithm.",
  3748. opt_n_threads,
  3749. algo_names[opt_algo]);
  3750. #endif
  3751. if (use_curses)
  3752. enable_curses();
  3753. watchdog_thr_id = mining_threads + 2;
  3754. thr = &thr_info[watchdog_thr_id];
  3755. /* start wakeup thread */
  3756. if (thr_info_create(thr, NULL, watchdog_thread, NULL))
  3757. quit(1, "wakeup thread create failed");
  3758. /* Create curses input thread for keyboard input */
  3759. input_thr_id = mining_threads + 4;
  3760. thr = &thr_info[input_thr_id];
  3761. if (thr_info_create(thr, NULL, input_thread, thr))
  3762. quit(1, "input thread create failed");
  3763. pthread_detach(thr->pth);
  3764. #if 0
  3765. #ifdef WANT_CPUMINE
  3766. /* Create reinit cpu thread */
  3767. cpur_thr_id = mining_threads + 5;
  3768. thr = &thr_info[cpur_thr_id];
  3769. thr->q = tq_new();
  3770. if (!thr->q)
  3771. quit(1, "tq_new failed for cpur_thr_id");
  3772. if (thr_info_create(thr, NULL, reinit_cpu, thr))
  3773. quit(1, "reinit_cpu thread create failed");
  3774. #endif
  3775. #endif
  3776. /* Create reinit gpu thread */
  3777. gpur_thr_id = mining_threads + 6;
  3778. thr = &thr_info[gpur_thr_id];
  3779. thr->q = tq_new();
  3780. if (!thr->q)
  3781. quit(1, "tq_new failed for gpur_thr_id");
  3782. if (thr_info_create(thr, NULL, reinit_gpu, thr))
  3783. quit(1, "reinit_gpu thread create failed");
  3784. /* Create API socket thread */
  3785. api_thr_id = mining_threads + 7;
  3786. thr = &thr_info[api_thr_id];
  3787. if (thr_info_create(thr, NULL, api_thread, thr))
  3788. quit(1, "API thread create failed");
  3789. pthread_detach(thr->pth);
  3790. sleep(opt_log_interval);
  3791. /* main loop - simply wait for workio thread to exit */
  3792. pthread_join(thr_info[work_thr_id].pth, NULL);
  3793. applog(LOG_INFO, "workio thread dead, exiting.");
  3794. gettimeofday(&total_tv_end, NULL);
  3795. disable_curses();
  3796. if (!opt_realquiet && successful_connect)
  3797. print_summary();
  3798. #ifdef HAVE_OPENCL
  3799. clear_adl(nDevs);
  3800. #endif
  3801. if (opt_n_threads)
  3802. free(cpus);
  3803. HASH_ITER(hh, staged_work, work, tmpwork) {
  3804. HASH_DEL(staged_work, work);
  3805. free_work(work);
  3806. }
  3807. HASH_ITER(hh, blocks, block, tmpblock) {
  3808. HASH_DEL(blocks, block);
  3809. free(block);
  3810. }
  3811. curl_global_cleanup();
  3812. return 0;
  3813. }