main.c 141 KB

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