-
Notifications
You must be signed in to change notification settings - Fork 537
Expand file tree
/
Copy pathshim.cpp
More file actions
3158 lines (2699 loc) · 87.8 KB
/
shim.cpp
File metadata and controls
3158 lines (2699 loc) · 87.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: Apache-2.0
// Copyright (C) 2016-2022 Xilinx, Inc. All rights reserved.
// Copyright (C) 2022-2025 Advanced Micro Devices, Inc. All rights reserved.
#include "shim.h"
#include "system_linux.h"
#include "hwctx_object.h"
#include "dev_zocl.h"
#include "core/include/shim_int.h"
#include "core/include/xdp/aim.h"
#include "core/include/xdp/am.h"
#include "core/include/xdp/asm.h"
#include "core/include/xdp/lapc.h"
#include "core/include/xdp/spc.h"
#include "core/include/xrt/xrt_uuid.h"
#include "core/include/deprecated/xcl_app_debug.h"
#include "core/edge/common/aie_parser.h"
#include "core/common/bo_cache.h"
#include "core/common/config_reader.h"
#include "core/common/config_reader.h"
#include "core/common/error.h"
#include "core/common/message.h"
#include "core/common/query_requests.h"
#include "core/common/scheduler.h"
#include "core/common/xclbin_parser.h"
#include <cassert>
#include <cerrno>
#include <chrono>
#include <cstdarg>
#include <cstring>
#include <filesystem>
#include <iostream>
#include <iomanip>
#include <thread>
#include <vector>
#include <regex>
#include <fcntl.h>
#include <poll.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include "plugin/xdp/hal_profile.h"
#ifndef __HWEM__
#include "plugin/xdp/hal_api_interface.h"
#endif
#include "plugin/xdp/shim_callbacks.h"
#if defined(XRT_ENABLE_LIBDFX)
extern "C" {
#include <libdfx.h>
}
#endif
namespace {
template <typename ...Args>
void
xclLog(xrtLogMsgLevel level, const char* format, Args&&... args)
{
auto slvl = static_cast<xrt_core::message::severity_level>(level);
xrt_core::message::send(slvl, "XRT", format, std::forward<Args>(args)...);
}
constexpr size_t
operator"" _gb(unsigned long long value)
{
return value << 30;
}
static ZYNQ::shim*
get_shim_object(xclDeviceHandle handle)
{
if (auto shim = ZYNQ::shim::handleCheck(handle))
return shim;
throw xrt_core::error("Invalid shim handle");
}
}
// TODO: This code is copy from core/pcie/linux/shim.cpp. Considering to create a util library for X86 and ARM.
// Copy bytes word (32bit) by word.
//
// Neither memcpy, nor std::copy work as they become byte copying on
// some platforms
inline void* wordcopy(void *dst, const void* src, size_t bytes)
{
// assert dest is 4 byte aligned
assert((reinterpret_cast<intptr_t>(dst) % 4) == 0);
using word = uint32_t;
auto d = reinterpret_cast<word*>(dst);
auto s = reinterpret_cast<const word*>(src);
auto w = bytes/sizeof(word);
for (size_t i=0; i<w; ++i)
{
d[i] = s[i];
}
return dst;
}
namespace ZYNQ {
//initializing static member
std::map<uint64_t, uint32_t *> shim::mKernelControl;
shim::
shim(unsigned index, std::shared_ptr<xrt_core::edge::dev_zocl> edev_zocl)
: mCoreDevice(xrt_core::edge_linux::get_userpf_device(this, index))
, mBoardNumber(index)
, mKernelClockFreq(100)
, mDev{std::move(edev_zocl)}
, mCuMaps(128, {nullptr, 0})
{
xclLog(XRT_INFO, "%s", __func__);
const std::string zocl_drm_device = "/dev/dri/" + get_render_devname();
mKernelFD = open(zocl_drm_device.c_str(), O_RDWR);
// Validity of mKernelFD is checked using handleCheck in every shim function
mCmdBOCache = std::make_unique<xrt_core::bo_cache>(this, xrt_core::config::get_cmdbo_cache());
}
shim::
~shim()
{
xclLog(XRT_INFO, "%s", __func__);
// Flush all of the profiling information from the device to the profiling
// library before the device is closed (when profiling is enabled).
xdp::finish_flush_device(this);
// The BO cache unmaps and releases all execbo, but this must
// be done before the device (mKernelFD) is closed.
mCmdBOCache.reset(nullptr);
if (mKernelFD > 0) {
close(mKernelFD);
}
for (auto p : mCuMaps) {
if (p.first)
(void) munmap(p.first, p.second);
}
}
// This function is for internal mapping CU and debug IP only.
// For the future, this could be used to support any address aperture.
int
shim::
mapKernelControl(const std::vector<std::pair<uint64_t, size_t>>& offsets)
{
void *ptr = NULL;
if (offsets.size() == 0) {
// The offsets list is empty. Just skip mapping.
return 0;
}
auto offset_it = offsets.begin();
auto end = offsets.end();
while (offset_it != end) {
// This (~0xFF) is the KDS mask
if ((offset_it->first & (~0xFF)) != (-1UL & ~0xFF)) {
auto it = mKernelControl.find(offset_it->first);
if (it == mKernelControl.end()) {
drm_zocl_info_cu info = {offset_it->first, -1, -1, 0};
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_INFO_CU, &info);
if (result) {
xclLog(XRT_ERROR, "%s: Failed to find CU info 0x%lx", __func__, offset_it->first);
return -errno;
}
size_t psize = getpagesize();
ptr = mmap(0, info.cu_size, PROT_READ | PROT_WRITE, MAP_SHARED, mKernelFD, info.apt_idx*psize);
if (ptr == MAP_FAILED) {
xclLog(XRT_ERROR, "%s: Map failed for aperture 0x%lx, size 0x%lx", __func__, offset_it->first, info.cu_size);
return -1;
}
mKernelControl.insert(it, std::pair<uint64_t, uint32_t *>(offset_it->first, (uint32_t *)ptr));
}
}
offset_it++;
}
return 0;
}
// This function is for internal use only.
// It is used to find CUs or Debug IP's virtual address.
void *
shim::
getVirtAddressOfApture(xclAddressSpace space, const uint64_t phy_addr, uint64_t& offset)
{
void *vaddr = NULL;
// If CU size is 64 Kb, then this is safe. For Debug/Profile IPs,
// they may have 4K or 8K register space. The profiling library
// will make sure that the offset will not be abused.
uint64_t mask;
if (space == XCL_ADDR_SPACE_DEVICE_PERFMON) {
// Try small aperture. If it fails, then try bigger apertures
mask = 0xFFF;
while (mask != 0x3FFF) {
vaddr = mKernelControl[phy_addr & ~mask];
if (vaddr) {
offset = phy_addr & mask ;
break ;
}
mask = (mask << 1) + 1;
}
}
if (!vaddr) {
// Try 64KB aperture
mask = 0xFFFF;
vaddr = mKernelControl[phy_addr & ~mask];
offset = phy_addr & mask;
}
if (!vaddr)
xclLog(XRT_ERROR, "%s: Could not found the mapped address. Check if XCLBIN is loaded.", __func__);
// If could not found the phy_addr in the mapping table, return will be NULL.
return vaddr;
}
// For xclRead and xclWrite. The offset is comming from XCLBIN.
// It is the physical address on MPSoC.
// It consists of base address of the aperture and offset in the aperture
// Now the aceptable aperture are CUs and Debug IPs
size_t
shim::
xclWrite(xclAddressSpace space, uint64_t offset, const void *hostBuf, size_t size)
{
uint64_t off;
void *vaddr = NULL;
if (!hostBuf) {
xclLog(XRT_ERROR, "%s: Invalid hostBuf.", __func__);
return -1;
}
vaddr = getVirtAddressOfApture(space, offset, off);
if (!vaddr) {
xclLog(XRT_ERROR, "%s: Invalid offset.", __func__);
return -1;
}
// Once reach here, vaddr and hostBuf should already be checked.
wordcopy((char *)vaddr + off, hostBuf, size);
return size;
}
size_t
shim::
xclRead(xclAddressSpace space, uint64_t offset, void *hostBuf, size_t size)
{
uint64_t off;
void *vaddr = NULL;
if (!hostBuf) {
xclLog(XRT_ERROR, "%s: Invalid hostBuf.", __func__);
return -1;
}
vaddr = getVirtAddressOfApture(space, offset, off);
if (!vaddr) {
xclLog(XRT_ERROR, "%s: Invalid offset.", __func__);
return -1;
}
// Once reach here, vaddr and hostBuf should already be checked.
wordcopy(hostBuf, (char *)vaddr + off, size);
return size;
}
std::unique_ptr<xrt_core::buffer_handle>
shim::
xclAllocBO(size_t size, unsigned flags, xrt_core::hwctx_handle* hwctx_hdl)
{
drm_zocl_create_bo info = { size, 0xffffffff, flags};
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_CREATE_BO, &info);
if (result)
throw std::bad_alloc();
xclLog(XRT_DEBUG, "%s: size %ld, flags 0x%x", __func__, size, flags);
xclLog(XRT_INFO, "%s: ioctl return %d, bo handle %d", __func__, result, info.handle);
return std::make_unique<buffer_object>(this, info.handle, hwctx_hdl);
}
std::unique_ptr<xrt_core::buffer_handle>
shim::
xclAllocUserPtrBO(void *userptr, size_t size, unsigned flags, xrt_core::hwctx_handle* hwctx_hdl)
{
flags |= DRM_ZOCL_BO_FLAGS_USERPTR;
drm_zocl_userptr_bo info = {reinterpret_cast<uint64_t>(userptr), size, 0xffffffff, flags};
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_USERPTR_BO, &info);
if (result)
throw std::bad_alloc();
xclLog(XRT_DEBUG, "%s: userptr %p size %ld, flags 0x%x", __func__, userptr, size, flags);
xclLog(XRT_INFO, "%s: ioctl return %d, bo handle %d", __func__, result, info.handle);
return std::make_unique<buffer_object>(this, info.handle, hwctx_hdl);
}
unsigned int
shim::
xclGetHostBO(uint64_t paddr, size_t size)
{
drm_zocl_host_bo info = {paddr, size, 0xffffffff};
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_GET_HOST_BO, &info);
xclLog(XRT_DEBUG, "%s: paddr 0x%lx, size %ld", __func__, paddr, size);
xclLog(XRT_INFO, "%s: ioctl return %d, bo handle %d", __func__, result, info.handle);
return info.handle;
}
void
shim::
xclFreeBO(unsigned int boHandle)
{
drm_gem_close closeInfo = {boHandle, 0};
int result = ioctl(mKernelFD, DRM_IOCTL_GEM_CLOSE, &closeInfo);
xclLog(XRT_DEBUG, "%s: boHandle %d, ioctl return %d", __func__, boHandle, result);
}
int
shim::
xclWriteBO(unsigned int boHandle, const void *src, size_t size, size_t seek)
{
drm_zocl_pwrite_bo pwriteInfo = { boHandle, 0, seek, size, reinterpret_cast<uint64_t>(src) };
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_PWRITE_BO, &pwriteInfo);
xclLog(XRT_DEBUG, "%s: boHandle %d, src %p, size %ld, seek %ld", __func__, boHandle, src, size, seek);
xclLog(XRT_INFO, "%s: ioctl return %d", __func__, result);
return result ? -errno : result;
}
int
shim::
xclReadBO(unsigned int boHandle, void *dst, size_t size, size_t skip)
{
drm_zocl_pread_bo preadInfo = { boHandle, 0, skip, size, reinterpret_cast<uint64_t>(dst) };
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_PREAD_BO, &preadInfo);
xclLog(XRT_DEBUG, "%s: boHandle %d, dst %p, size %ld, skip %ld", __func__, boHandle, dst, size, skip);
xclLog(XRT_INFO, "%s: ioctl return %d", __func__, result);
return result ? -errno : result;
}
void *
shim::
xclMapBO(unsigned int boHandle, bool write)
{
drm_zocl_info_bo info = { boHandle, 0, 0 };
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_INFO_BO, &info);
drm_zocl_map_bo mapInfo = { boHandle, 0, 0 };
result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_MAP_BO, &mapInfo);
if (result) {
xclLog(XRT_ERROR, "%s: ZOCL_MAP_BO ioctl return %d", __func__, result);
return NULL;
}
void *ptr = mmap(0, info.size, (write ?(PROT_READ|PROT_WRITE) : PROT_READ ),
MAP_SHARED, mKernelFD, mapInfo.offset);
xclLog(XRT_INFO, "%s: mmap return %p", __func__, ptr);
return ptr;
}
int
shim::
xclUnmapBO(unsigned int boHandle, void* addr)
{
drm_zocl_info_bo info = { boHandle, 0, 0 };
int ret = ioctl(mKernelFD, DRM_IOCTL_ZOCL_INFO_BO, &info);
if (ret)
return -errno;
return munmap(addr, info.size);
}
int
shim::
xclGetDeviceInfo2(xclDeviceInfo2 *info)
{
std::memset(info, 0, sizeof(xclDeviceInfo2));
info->mMagic = 0X586C0C6C;
info->mHALMajorVersion = XCLHAL_MAJOR_VER;
info->mHALMajorVersion = XCLHAL_MINOR_VER;
info->mMinTransferSize = 32;
info->mVendorId = 0x10ee; // TODO: UKP
info->mDeviceId = 0xffff; // TODO: UKP
info->mSubsystemId = 0xffff;
info->mSubsystemVendorId = 0xffff;
info->mDeviceVersion = 0xffff;
info->mDDRSize = 4_gb;
info->mDataAlignment = BUFFER_ALIGNMENT; //TODO:UKP
info->mDDRBankCount = 1;
info->mOCLFrequency[0] = mKernelClockFreq;
info->mTimeStamp = 0;
#if defined(__aarch64__)
info->mNumCDMA = 1;
#else
info->mNumCDMA = 0;
#endif
std::string deviceName("edge");
mVBNV.open("/etc/xocl.txt");
if (mVBNV.is_open()) {
mVBNV >> deviceName;
}
mVBNV.close();
std::size_t length = deviceName.copy(info->mName, deviceName.length(),0);
info->mName[length] = '\0';
return 0;
}
int
shim::
xclSyncBO(unsigned int boHandle, xclBOSyncDirection dir, size_t size, size_t offset)
{
drm_zocl_sync_bo_dir zocl_dir;
if (dir == XCL_BO_SYNC_BO_TO_DEVICE)
zocl_dir = DRM_ZOCL_SYNC_BO_TO_DEVICE;
else if (dir == XCL_BO_SYNC_BO_FROM_DEVICE)
zocl_dir = DRM_ZOCL_SYNC_BO_FROM_DEVICE;
else
return -EINVAL;
drm_zocl_sync_bo syncInfo = { boHandle, zocl_dir, offset, size };
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_SYNC_BO, &syncInfo);
xclLog(XRT_DEBUG, "%s: boHandle %d, dir %d, size %ld, offset %ld", __func__, boHandle, dir, size, offset);
xclLog(XRT_INFO, "%s: ioctl return %d", __func__, result);
return result ? -errno : result;
}
int
shim::
xclCopyBO(unsigned int dst_boHandle, unsigned int src_boHandle, size_t size,
size_t dst_offset, size_t src_offset)
{
int ret = -EOPNOTSUPP;
#ifdef __aarch64__
auto bo = mCmdBOCache->alloc<ert_start_copybo_cmd>();
ert_fill_copybo_cmd(bo.second, src_boHandle, dst_boHandle,
src_offset, dst_offset, size);
auto boh = static_cast<buffer_object*>(bo.first.get());
ret = xclExecBuf(boh->get_handle());
if (ret) {
mCmdBOCache->release(std::move(bo));
return ret;
}
do {
ret = xclExecWait(1000);
if (ret == -1)
break;
}
while (bo.second->state < ERT_CMD_STATE_COMPLETED);
ret = (ret == -1) ? -errno : 0;
if (!ret && (bo.second->state != ERT_CMD_STATE_COMPLETED))
ret = -EINVAL;
mCmdBOCache->release(std::move(bo));
#endif
xclLog(XRT_INFO, "%s: return %d", __func__, ret);
return ret;
}
int
shim::
xclLoadXclBin(const xclBin *buffer)
{
auto top = reinterpret_cast<const axlf*>(buffer);
auto ret = xclLoadAxlf(top);
if (!ret && !xrt_core::xclbin::is_aie_only(top))
mKernelClockFreq = xrt_core::xclbin::get_kernel_freq(top);
xclLog(XRT_INFO, "%s: return %d", __func__, ret);
return ret;
}
#if defined(XRT_ENABLE_LIBDFX)
namespace libdfx {
static void
libdfxHelper(std::shared_ptr<xrt_core::device> core_dev, std::string& dtbo_path, int& fd)
{
uint32_t slot_id = 0;
static const std::string dtbo_dir_path = "/configfs/device-tree/overlays/";
// root privileges are needed for loading and unloading dtbo and bitstream
if (getuid() && geteuid())
throw std::runtime_error("Root privileges required");
/*
* get dtbo_path of slot '0' for now, in future when we support multi slot we need
* info about which slot this xclbin needs to be loaded
* TODO: read slot id from xclbin or get it as an arg to this function
*/
try {
dtbo_path = xrt_core::device_query<xrt_core::query::dtbo_path>(core_dev, slot_id);
}
catch(const std::exception &e) {
const std::string errmsg{"Query for dtbo path failed: "};
throw std::runtime_error(errmsg + e.what());
}
if (!dtbo_path.empty()) {
// remove existing libdfx node
rmdir((dtbo_dir_path + dtbo_path).c_str());
dtbo_path.clear();
// close drm fd as zocl driver will be reloaded
close(fd);
}
else {
// bitstream is loaded for first time
std::filesystem::directory_iterator end_itr;
static const std::regex filter{".*_image_[0-9]+"};
for (std::filesystem::directory_iterator itr( dtbo_dir_path ); itr != end_itr; ++itr) {
if (!std::regex_match(itr->path().filename().string(), filter))
continue;
// remove existing libdfx node loaded by libdfx daemon
rmdir((dtbo_dir_path + itr->path().filename().string()).c_str());
}
}
}
static void
copyBufferToFile(const std::string& file_path, const char* buf, uint64_t size)
{
std::ofstream file(file_path, std::ios::out | std::ios::binary);
if (!file)
throw std::runtime_error("Failed to open " + file_path + " for writing xclbin section");
file.write(buf, size);
file.close();
}
static void
libdfxConfig(std::string& xclbin_dir_path, const axlf *top,
const axlf_section_header *bit_header, const axlf_section_header *overlay_header)
{
// create a temp directory to extract bitstream and dtbo
char dir[] = "/tmp/xclbin.XXXXXX";
char *tmpdir = mkdtemp(dir);
if (tmpdir == nullptr)
throw std::runtime_error("Failed to create tmp directory for xclbin files extraction");
xclbin_dir_path = tmpdir;
// create a file with BITSTREAM section
const std::string bit_file_path = xclbin_dir_path + "/xclbin.bit";
auto bit_buffer = reinterpret_cast<const char *>(top) + bit_header->m_sectionOffset;
copyBufferToFile(bit_file_path, bit_buffer, bit_header->m_sectionSize);
// create a file with OVERLAY(dtbo) section
const std::string overlay_file_path = xclbin_dir_path + "/xclbin.dtbo";
auto overlay_buffer = reinterpret_cast<const char *>(top) + overlay_header->m_sectionOffset;
copyBufferToFile(overlay_file_path, overlay_buffer, overlay_header->m_sectionSize);
}
// function for cleaning temp files
static void
libdfxClean(const std::string& file_path)
{
try {
if (std::filesystem::exists(std::filesystem::path(file_path)))
std::filesystem::remove_all(std::filesystem::path(file_path));
}
catch(std::exception& ex) {
xclLog(XRT_WARNING, "%s: unable to remove '%s' folder",__func__,file_path);
}
}
static int
libdfxLoadAxlf(std::shared_ptr<xrt_core::device> core_dev, const axlf *top,
const axlf_section_header *overlay_header, int& fd, int flags, std::string& dtbo_path)
{
static const std::string fpga_device = "/dev/fpga0";
// check BITSTREAM section
const axlf_section_header *bit_header = xclbin::get_axlf_section(top, axlf_section_kind::BITSTREAM);
if (!bit_header)
throw std::runtime_error("No BITSTREAM section in xclbin");
//check if xclbin is already loaded
try {
if (core_dev->get_xclbin_uuid() == xrt::uuid(top->m_header.uuid) && !(flags & DRM_ZOCL_FORCE_PROGRAM)) {
xclLog(XRT_WARNING, "%s: skipping as xclbin is already loaded", __func__);
return 1;
}
}
catch(const std::exception &e) {
// can happen when no bitstream is loaded and xclbinid sysfs is not created
// do nothing
}
libdfxHelper(core_dev, dtbo_path, fd);
std::string xclbin_dir_path;
libdfxConfig(xclbin_dir_path, top, bit_header, overlay_header);
// call libdfx api to load bitstream and dtbo
int dtbo_id = dfx_cfg_init(xclbin_dir_path.c_str(), fpga_device.c_str(), 0);
if (dtbo_id <= 0) {
libdfxClean(xclbin_dir_path);
throw std::runtime_error("Failed to initialize config with libdfx api");
}
if (dfx_cfg_load(dtbo_id)){
dfx_cfg_destroy(dtbo_id);
libdfxClean(xclbin_dir_path);
throw std::runtime_error("Failed to load bitstream, dtbo with libdfx api");
}
// save dtbo_path as load is successful
dtbo_path = std::filesystem::path(xclbin_dir_path).filename().string()
+ "_image_" + std::to_string(dtbo_id);
// clean tmp files of libdfx
dfx_cfg_destroy(dtbo_id);
libdfxClean(xclbin_dir_path);
// asynchronously check for drm device node
const static int timeout_sec = 10;
int count = 0;
const std::string render_dev_dir{"/dev/dri/"};
std::string zocl_drm_device;
while (count++ < timeout_sec) {
zocl_drm_device = render_dev_dir + get_render_devname();
if (std::filesystem::exists(std::filesystem::path(zocl_drm_device)))
break;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
// create drm fd
fd = open(zocl_drm_device.c_str(), O_RDWR);
if (fd < 0) {
dtbo_path.clear();
throw std::runtime_error("Cannot create file descriptor with device " + zocl_drm_device);
}
return 0;
}
}
#endif
int
shim::
xclLoadAxlf(const axlf *buffer)
{
int ret = 0;
unsigned int flags = DRM_ZOCL_PLATFORM_BASE;
int off = 0;
std::string dtbo_path("");
#ifndef __HWEM__
auto is_pr_platform = buffer->m_header.m_mode == XCLBIN_PR;
auto is_flat_enabled = xrt_core::config::get_enable_flat(); //default value is false
auto force_program = xrt_core::config::get_force_program_xclbin(); //default value is false
auto overlay_header = xclbin::get_axlf_section(buffer, axlf_section_kind::OVERLAY);
if (is_pr_platform)
flags = DRM_ZOCL_PLATFORM_PR;
/*
* If its non-PR-platform and enable_flat=true in xrt.ini, download the full
* bitstream. But if OVERLAY section is present in xclbin, userspace apis are
* used to download full bitstream
*/
else if (is_flat_enabled && !overlay_header) {
if (!ZYNQ::shim::handleCheck(this)) {
xclLog(XRT_ERROR, "%s: No DRM render device found", __func__);
return -ENODEV;
}
flags = DRM_ZOCL_PLATFORM_FLAT;
}
if (force_program) {
flags = flags | DRM_ZOCL_FORCE_PROGRAM;
}
#if defined(XRT_ENABLE_LIBDFX)
// if OVERLAY section is present use libdfx apis to load bitstream and dtbo(overlay)
if(overlay_header) {
try {
// if xclbin is already loaded ret val is '1', dont call ioctl in this case
if (libdfx::libdfxLoadAxlf(this->mCoreDevice, buffer, overlay_header, mKernelFD, flags, dtbo_path))
return 0;
}
catch(const std::exception& e){
xclLog(XRT_ERROR, "%s: loading xclbin with OVERLAY section failed: %s", __func__,e.what());
return -EPERM;
}
}
#endif
#endif
/* Get the AIE_METADATA and get the hw_gen information */
uint8_t hw_gen = xrt_core::edge::aie::get_hw_gen(mCoreDevice.get());
auto partition_id = xrt_core::edge::aie::full_array_id;
drm_zocl_axlf axlf_obj = {
.za_xclbin_ptr = const_cast<axlf *>(buffer),
.za_flags = flags,
.za_ksize = 0,
.za_kernels = NULL,
.za_slot_id = 0, // TODO Cleanup: Once uuid interface id available we need to remove this
.za_dtbo_path = const_cast<char *>(dtbo_path.c_str()),
.za_dtbo_path_len = static_cast<unsigned int>(dtbo_path.length()),
.hw_gen = hw_gen,
.partition_id = static_cast<unsigned int>(partition_id),
};
axlf_obj.kds_cfg.polling = xrt_core::config::get_ert_polling();
std::vector<char> krnl_binary;
auto xml_header = xclbin::get_axlf_section(buffer, axlf_section_kind::EMBEDDED_METADATA);
if (xml_header) {
auto kernels = xrt_core::xclbin::get_kernels(buffer);
/* Calculate size of kernels */
for (auto& kernel : kernels) {
axlf_obj.za_ksize += sizeof(kernel_info) + sizeof(argument_info) * kernel.args.size();
}
/* Check PCIe's shim.cpp for details of kernels binary */
krnl_binary.resize(axlf_obj.za_ksize);
axlf_obj.za_kernels = krnl_binary.data();
for (auto& kernel : kernels) {
auto krnl = reinterpret_cast<kernel_info *>(axlf_obj.za_kernels + off);
if (kernel.name.size() > sizeof(krnl->name))
return -EINVAL;
auto len = std::min(kernel.name.size(), sizeof(krnl->name) - 1);
std::memcpy(krnl->name, kernel.name.c_str(), len);
krnl->name[len] = '\0';
krnl->range = kernel.range;
krnl->anums = kernel.args.size();
krnl->features = 0;
if (kernel.sw_reset)
krnl->features |= KRNL_SW_RESET;
int ai = 0;
for (auto& arg : kernel.args) {
if (arg.name.size() > sizeof(krnl->args[ai].name)) {
xclLog(XRT_ERROR, "%s: Argument name length %d>%d", __func__, arg.name.size(), sizeof(krnl->args[ai].name));
return -EINVAL;
}
auto arg_len = std::min(arg.name.size(), sizeof(krnl->args[ai].name) - 1);
std::memcpy(krnl->args[ai].name, arg.name.c_str(), arg_len);
krnl->args[ai].name[arg_len] = '\0';
krnl->args[ai].offset = arg.offset;
krnl->args[ai].size = arg.size;
// XCLBIN doesn't define argument direction yet and it only support
// input arguments.
// Driver use 1 for input argument and 2 for output.
// Let's refine this line later.
krnl->args[ai].dir = 1;
ai++;
}
off += sizeof(kernel_info) + sizeof(argument_info) * kernel.args.size();
}
}
#ifdef __HWEM__
if (!secondXclbinLoadCheck(this->mCoreDevice, buffer)) {
return 0; // skipping to load the 2nd xclbin for hw_emu embedded designs
}
#endif
ret = ioctl(mKernelFD, DRM_IOCTL_ZOCL_READ_AXLF, &axlf_obj);
xclLog(XRT_INFO, "%s: flags 0x%x, return %d", __func__, flags, ret);
return ret ? -errno : ret;
}
int
shim::
secondXclbinLoadCheck(std::shared_ptr<xrt_core::device> core_dev, const axlf *top) {
try {
static int xclbin_hw_emu_count = 0;
if (core_dev->get_xclbin_uuid() != xrt::uuid(top->m_header.uuid)) {
xclbin_hw_emu_count++;
if (xclbin_hw_emu_count > 1) {
xclLog(XRT_WARNING, "%s: Skipping as xclbin is already loaded. Only single XCLBIN load is supported for hw_emu embedded designs.", __func__);
return 0;
}
} else {
xclLog(XRT_INFO, "%s: Loading the XCLBIN", __func__);
}
}
catch(const std::exception &e) {
// do nothing
}
return 1;
}
std::unique_ptr<xrt_core::shared_handle>
shim::
xclExportBO(unsigned int boHandle)
{
drm_prime_handle info = {boHandle, DRM_RDWR, -1};
// Since Linux 4.6, drm_prime_handle_to_fd_ioctl respects O_RDWR.
int result = ioctl(mKernelFD, DRM_IOCTL_PRIME_HANDLE_TO_FD, &info);
if (result) {
xclLog(XRT_WARNING, "%s: DRM prime handle to fd faied with DRM_RDWR. Try default flags.", __func__);
info.flags = 0;
result = ioctl(mKernelFD, DRM_IOCTL_PRIME_HANDLE_TO_FD, &info);
}
if (result)
throw xrt_core::system_error(result, "failed to export bo");
xclLog(XRT_INFO, "%s: boHandle %d, ioctl return %ld, fd %d", __func__, boHandle, result, info.fd);
return std::make_unique<shared_object>(this, info.fd);
}
std::unique_ptr<xrt_core::buffer_handle>
shim::
xclImportBO(int fd, unsigned flags)
{
drm_prime_handle info = {0xffffffff, flags, fd};
int result = ioctl(mKernelFD, DRM_IOCTL_PRIME_FD_TO_HANDLE, &info);
if (result)
throw xrt_core::system_error(result, "ioctl failed to import bo");
xclLog(XRT_INFO, "%s: fd %d, flags %x, ioctl return %d, bo handle %d", __func__, fd, flags, result, info.handle);
return std::make_unique<buffer_object>(this, info.handle);
}
unsigned int
shim::
xclGetBOProperties(unsigned int boHandle, xclBOProperties *properties)
{
drm_zocl_info_bo info = {boHandle, 0, 0, 0};
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_INFO_BO, &info);
properties->handle = info.handle;
properties->flags = info.flags;
properties->size = info.size;
properties->paddr = info.paddr;
xclLog(XRT_DEBUG, "%s: boHandle %d, size %x, paddr 0x%lx", __func__, boHandle, info.size, info.paddr);
return result ? -errno : result;
}
bool
shim::
isGood() const
{
if(mKernelFD < 0)
return false;
return true;
}
shim *
shim::
handleCheck(void *handle, bool checkDrmFd /*= true*/)
{
// Sanity checks
if (!handle)
return 0;
if (checkDrmFd && !((shim *) handle)->isGood()) {
return 0;
}
return (shim *) handle;
}
int
shim::
xclExecBuf(unsigned int cmdBO)
{
drm_zocl_execbuf exec = {0, cmdBO};
int result = ioctl(mKernelFD, DRM_IOCTL_ZOCL_EXECBUF, &exec);
xclLog(XRT_DEBUG, "%s: cmdBO handle %d, ioctl return %d", __func__, cmdBO, result);
if (result == -EDEADLK)
xclLog(XRT_ERROR, "CU might hang, please reset device");
return result ? -errno : result;
}
int
shim::
xclExecWait(int timeoutMilliSec)
{
std::vector<pollfd> uifdVector;
pollfd info = {mKernelFD, POLLIN, 0};
uifdVector.push_back(info);
return poll(&uifdVector[0], uifdVector.size(), timeoutMilliSec);
}
uint
shim::
xclGetNumLiveProcesses()
{
return 0;
}
std::string
shim::
xclGetSysfsPath(const std::string& entry)
{
return mDev->get_sysfs_path(entry);
}
int
shim::
xclGetDebugIPlayoutPath(char* layoutPath, size_t size)
{
std::string path = xclGetSysfsPath("debug_ip_layout");
if (path.size() >= size)
return -EINVAL;
auto len = std::min(path.size(), size - 1);
std::memcpy(layoutPath, path.c_str(), len);
layoutPath[len] = '\0';
return 0;
}
int
shim::
xclGetTraceBufferInfo(uint32_t nSamples, uint32_t& traceSamples, uint32_t& traceBufSz)
{
// On Zynq, we are currently storing 2 samples per packet in the FIFO
traceSamples = nSamples/2;
traceBufSz = sizeof(uint32_t) * nSamples;
return 0;
}
int
shim::
xclReadTraceData(void* traceBuf, uint32_t traceBufSz, uint32_t numSamples, uint64_t ipBaseAddress, uint32_t& wordsPerSample)
{
uint32_t *buffer = (uint32_t*)traceBuf;
for(uint32_t i = 0 ; i < numSamples; i++) {
// Read only one 32-bit value. Later (in xdp layer) assemble two 32-bit values to form one trace sample.
// Here numSamples is the total number of reads required
xclRead(XCL_ADDR_SPACE_DEVICE_PERFMON, ipBaseAddress + 0x1000, (buffer + i), sizeof(uint32_t));
}
wordsPerSample = 2;
return 0;
}
// For DDR4: Typical Max BW = 19.25 GB/s
double
shim::
xclGetHostReadMaxBandwidthMBps()
{
return 19250.00;
}
// For DDR4: Typical Max BW = 19.25 GB/s
double
shim::
xclGetHostWriteMaxBandwidthMBps()
{
return 19250.00;
}
// For DDR4: Typical Max BW = 19.25 GB/s
double
shim::
xclGetKernelReadMaxBandwidthMBps()
{
return 19250.00;
}