cgminer.c 121 KB

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