cgminer.c 117 KB

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