luwen-if 0.4.4

Generic interface to Tenstorrent ai accelerators, abstracting the details of communication
Documentation
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
// SPDX-FileCopyrightText: © 2023 Tenstorrent Inc.
// SPDX-License-Identifier: Apache-2.0

use std::sync::Arc;

use rust_embed::RustEmbed;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use super::chip_interface::ChipInterface;

#[derive(Error, Debug)]
pub enum AxiError {
    #[error("Invalid path: {key} specifically was not able to find {path}")]
    InvalidPath { key: String, path: String },

    #[error("Invalid path: {key} specifically was not able to parse {path} as an array def.")]
    InvalidArrayPath { key: String, path: String },

    #[error("No AXI data table loaded")]
    NoAxiData,

    #[error("The readbuffer is not large enough to hold the requested data")]
    ReadBufferTooSmall,

    #[error("The writebuffer is not the same size as the requested field")]
    WriteBufferMismatch,
}

#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AxiData {
    pub addr: u64,
    pub size: u64,
    pub bits: Option<(u32, u32)>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct MemorySlice {
    pub name: String,
    pub offset: u64,
    pub size: u64,
    pub array_count: Option<u64>,
    pub bit_mask: Option<(u32, u32)>,
    pub children: std::collections::HashMap<String, MemorySlice>,
}

#[derive(Serialize, Deserialize)]
pub enum MemorySlices {
    Flat(std::collections::HashMap<String, AxiData>),
    Tree(std::collections::HashMap<String, MemorySlice>),
}

#[derive(RustEmbed)]
#[folder = "axi-data"]
struct WHPciData;

pub fn load_axi_table(file: &str, _version: u32) -> MemorySlices {
    let data = WHPciData::get(file).unwrap();
    bincode::deserialize(&data.data).unwrap()
}

/// This is a generic trait which defines the high level chip communication primatives.
/// It's functions allow for the reading and writing of data to arbirary noc endpoints on any chip
/// with the details of how the endpoint is accessed abstracted away.
///
/// For the ARC endpoint special functions are defined because unlike most noc endpoints the ARC addresses
/// are mapped into the pci BAR address space.
pub trait ChipComms {
    /// Translate a String path into the corresponding AXI address.
    fn axi_translate(&self, addr: &str) -> Result<AxiData, AxiError>;
    /// Read and write to the NOC using AXI address gotten from `axi_translate`.
    fn axi_read(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>>;
    fn axi_write(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>>;

    /// Read and write to a noc endpoint, this could be a local or remote chip.
    fn noc_read(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>>;
    fn noc_write(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>>;
    fn noc_broadcast(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>>;

    /// Convenience functions for reading and writing 32 bit values.
    fn noc_read32(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
    ) -> Result<u32, Box<dyn std::error::Error>> {
        let mut value = [0; 4];
        self.noc_read(chip_if, noc_id, x, y, addr, &mut value)?;
        Ok(u32::from_le_bytes(value))
    }

    fn noc_write32(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        value: u32,
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.noc_write(chip_if, noc_id, x, y, addr, value.to_le_bytes().as_slice())
    }

    fn noc_broadcast32(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        addr: u64,
        value: u32,
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.noc_broadcast(chip_if, noc_id, addr, value.to_le_bytes().as_slice())
    }

    fn axi_read32(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
    ) -> Result<u32, Box<dyn std::error::Error>> {
        let mut value = [0; 4];
        self.axi_read(chip_if, addr, &mut value)?;
        Ok(u32::from_le_bytes(value))
    }

    fn axi_write32(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        value: u32,
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.axi_write(chip_if, addr, value.to_le_bytes().as_slice())
    }

    fn axi_sread32(
        &self,
        chip_if: &dyn ChipInterface,
        addr: &str,
    ) -> Result<u32, Box<dyn std::error::Error>> {
        let addr = self.axi_translate(addr.as_ref())?.addr;

        let mut value = [0; 4];
        self.axi_read(chip_if, addr, &mut value)?;
        Ok(u32::from_le_bytes(value))
    }

    fn axi_swrite32(
        &self,
        chip_if: &dyn ChipInterface,
        addr: &str,
        value: u32,
    ) -> Result<(), Box<dyn std::error::Error>> {
        let addr = self.axi_translate(addr.as_ref())?.addr;

        self.axi_write(chip_if, addr, &value.to_le_bytes())?;
        Ok(())
    }
}

pub fn axi_translate_tree(
    data: &std::collections::HashMap<String, MemorySlice>,
    addr: &str,
) -> Result<AxiData, AxiError> {
    let mut it = data;

    let mut offset = 0;
    let mut size = 0;
    let mut bits = None;
    for key in addr.split('.') {
        let (slice, index) = if !it.contains_key(key) && key.contains('[') {
            let mut parts = key.split('[');
            let key = parts.next().ok_or_else(|| AxiError::InvalidArrayPath {
                key: key.to_string(),
                path: addr.to_string(),
            })?;
            let index = parts
                .next()
                .ok_or_else(|| AxiError::InvalidArrayPath {
                    key: key.to_string(),
                    path: addr.to_string(),
                })?
                .trim_end_matches(']')
                .parse::<u64>()
                .map_err(|_| AxiError::InvalidArrayPath {
                    key: key.to_string(),
                    path: addr.to_string(),
                })?;

            (it.get(key), Some(index))
        } else {
            (it.get(key), None)
        };

        if let Some(slice) = slice {
            it = &slice.children;
            if let (Some(count), Some(index)) = (slice.array_count, index) {
                assert!(index < count);
            } else if index.is_some() ^ slice.array_count.is_some() {
                dbg!(slice);
                panic!("Tried to index a non-array or no index for array with {key}")
            }

            size = slice.size;
            bits = slice.bit_mask.clone();
            offset += slice.offset + slice.size * index.unwrap_or(0);
        } else {
            return Err(AxiError::InvalidPath {
                path: addr.to_string(),
                key: key.to_string(),
            });
        }
    }

    Ok(AxiData {
        addr: offset,
        size,
        bits,
    })
}

pub fn axi_translate(data: Option<&MemorySlices>, addr: &str) -> Result<AxiData, AxiError> {
    match data.ok_or(AxiError::NoAxiData)? {
        MemorySlices::Flat(data) => {
            if let Some(data) = data.get(addr) {
                Ok(data.clone())
            } else {
                Err(AxiError::InvalidPath {
                    path: addr.to_string(),
                    key: addr.to_string(),
                })
            }
        }
        MemorySlices::Tree(data) => axi_translate_tree(data, addr),
    }
}

pub struct ArcIf {
    pub axi_data: MemorySlices,
}

impl ChipComms for ArcIf {
    fn axi_translate(&self, addr: &str) -> Result<AxiData, AxiError> {
        axi_translate(Some(&self.axi_data), addr)
    }

    fn axi_read(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        chip_if.axi_read(addr as u32, data)
    }

    fn axi_write(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        chip_if.axi_write(addr as u32, data)
    }

    fn noc_read(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        chip_if.noc_read(noc_id, x, y, addr, data)
    }

    fn noc_write(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        chip_if.noc_write(noc_id, x, y, addr, data)
    }

    fn noc_broadcast(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        chip_if.noc_broadcast(noc_id, addr, data)
    }
}

impl ChipComms for Arc<dyn ChipComms> {
    fn axi_translate(&self, addr: &str) -> Result<AxiData, AxiError> {
        self.as_ref().axi_translate(addr)
    }

    fn axi_read(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().axi_read(chip_if, addr, data)
    }

    fn axi_write(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().axi_write(chip_if, addr, data)
    }

    fn noc_read(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().noc_read(chip_if, noc_id, x, y, addr, data)
    }

    fn noc_write(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().noc_write(chip_if, noc_id, x, y, addr, data)
    }

    fn noc_broadcast(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().noc_broadcast(chip_if, noc_id, addr, data)
    }
}

impl ChipComms for Arc<dyn ChipComms + Send + Sync> {
    fn axi_translate(&self, addr: &str) -> Result<AxiData, AxiError> {
        self.as_ref().axi_translate(addr)
    }

    fn axi_read(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().axi_read(chip_if, addr, data)
    }

    fn axi_write(
        &self,
        chip_if: &dyn ChipInterface,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().axi_write(chip_if, addr, data)
    }

    fn noc_read(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &mut [u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().noc_read(chip_if, noc_id, x, y, addr, data)
    }

    fn noc_write(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        x: u8,
        y: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().noc_write(chip_if, noc_id, x, y, addr, data)
    }

    fn noc_broadcast(
        &self,
        chip_if: &dyn ChipInterface,
        noc_id: u8,
        addr: u64,
        data: &[u8],
    ) -> Result<(), Box<dyn std::error::Error>> {
        self.as_ref().noc_broadcast(chip_if, noc_id, addr, data)
    }
}