cgminer.c 133 KB

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