cgminer.c 146 KB

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