miner.c 137 KB

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