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
//! The SMBus specific CMTP response protocol implementation.

use crate::control_packet::{
    CommandCode, CompletionCode, MCTPControlMessageHeader, MCTPGetEndpointIDEndpointIDType,
    MCTPGetEndpointIDEndpointType, MCTPSetEndpointIDAllocationStatus,
    MCTPSetEndpointIDAssignmentStatus,
};
use crate::mctp_traits::SMBusMCTPRequestResponse;
use core::cell::Cell;

/// The context for MCTP SMBus response protocol operations
pub struct MCTPSMBusContextResponse {
    address: u8,
    eid: Cell<u8>,
}

impl SMBusMCTPRequestResponse for MCTPSMBusContextResponse {
    /// Get the address of the device
    ///
    /// Returns the address
    fn get_address(&self) -> u8 {
        self.address
    }

    /// Get the current EID of the device
    ///
    /// Returns the EID
    fn get_eid(&self) -> u8 {
        self.eid.get()
    }

    /// Set the EID of the device
    ///
    /// `eid`: The new eid to use
    fn set_eid(&self, eid: u8) {
        self.eid.replace(eid);
    }
}

impl MCTPSMBusContextResponse {
    /// Create a new SBMust response context
    ///
    /// `address`: The source address of this device
    pub fn new(address: u8) -> Self {
        Self {
            address,
            eid: Cell::new(0x00),
        }
    }

    /// Assigns an EID to the endpoint at the given physical address
    ///
    /// `completion_code`: Indicates the completion code we should return.
    /// `dest_addr`: The address to send the data to.
    /// `assignment_status`: EID assignment status
    /// `allocation_status`: Endpoint ID allocation status
    /// `buf`: A mutable buffer to store the request bytes.
    ///
    /// EID dynamic Pools are not supported
    ///
    /// Returns the length of the query on success.
    pub fn set_endpoint_id(
        &self,
        completion_code: CompletionCode,
        dest_addr: u8,
        assignment_status: MCTPSetEndpointIDAssignmentStatus,
        allocation_status: MCTPSetEndpointIDAllocationStatus,
        buf: &mut [u8],
    ) -> Result<usize, ()> {
        let command_header =
            MCTPControlMessageHeader::new(false, false, 0, CommandCode::SetEndpointID);
        let message_header = Some(&(command_header.0[..]));
        // Return
        //  * Completion code
        //  * EID Assignment Status/Endpoint ID allocation status
        //  * EID Setting
        //  * EID Pool Size
        let mut message_data: [u8; 4] = [
            completion_code as u8,
            allocation_status as u8,
            self.eid.get(),
            0x00,
        ];

        if assignment_status == MCTPSetEndpointIDAssignmentStatus::Rejected {
            message_data[1] |= 1 << 4;
        }

        self.generate_packet_bytes(dest_addr, &message_header, &message_data, buf)
    }

    /// Returns the EID presently assigned to an endpoint. Also returns
    /// information about what type the endpoint is and its level of use of
    /// static EIDs.
    ///
    /// `completion_code`: Indicates the completion code we should return.
    /// `dest_addr`: The address to send the data to.
    /// `endpoint_type`: Endpoint Type
    /// `endpoint_id_type`: Endpoint ID Type
    /// `fairness_support`: fairness arbitration support (see 6.13)
    /// `buf`: A mutable buffer to store the request bytes.
    ///
    /// Returns the length of the query on success.
    pub fn get_endpoint_id(
        &self,
        completion_code: CompletionCode,
        dest_addr: u8,
        endpoint_type: MCTPGetEndpointIDEndpointType,
        endpoint_id_type: MCTPGetEndpointIDEndpointIDType,
        fairness_support: bool,
        buf: &mut [u8],
    ) -> Result<usize, ()> {
        let command_header =
            MCTPControlMessageHeader::new(false, false, 0, CommandCode::GetEndpointID);
        let message_header = Some(&(command_header.0[..]));
        // Return
        //  * Completion code
        //  * Endpoint ID
        //  * Endpoint Type (single endpoint)
        //  * Medium-Specific Information
        let message_data: [u8; 4] = [
            completion_code as u8,
            self.eid.get(),
            (endpoint_type as u8) << 4 | endpoint_id_type as u8,
            fairness_support as u8,
        ];

        self.generate_packet_bytes(dest_addr, &message_header, &message_data, buf)
    }

    /// Retrieves a per-device unique UUID associated with the endpoint
    ///
    /// `completion_code`: Indicates the completion code we should return.
    /// `dest_addr`: The address to send the data to.
    /// `uuid`: A reference to an array containing the UUID
    /// `buf`: A mutable buffer to store the request bytes.
    ///
    /// Returns the length of the query on success.
    pub fn get_endpoint_uuid(
        &self,
        completion_code: CompletionCode,
        dest_addr: u8,
        uuid: &[u8; 16],
        buf: &mut [u8],
    ) -> Result<usize, ()> {
        let command_header =
            MCTPControlMessageHeader::new(false, false, 0, CommandCode::GetEndpointUUID);
        let message_header = Some(&(command_header.0[..]));
        // Return
        //  * Completion code
        //  * UUID
        //  * Endpoint Type (single endpoint)
        //  * Medium-Specific Information
        let mut message_data: [u8; 17] = [0; 17];
        message_data[0] = completion_code as u8;
        message_data[1..17].copy_from_slice(uuid);

        self.generate_packet_bytes(dest_addr, &message_header, &message_data, buf)
    }

    /// Generate a response to the MCTP Version request supported by a device.
    ///
    /// `completion_code`: Indicates the completion code we should return.
    /// `dest_addr`: The address to send the data to.
    /// `buf`: A mutable buffer to store the request bytes.
    ///
    /// Returns the length of the response.
    pub fn get_mctp_version_support(
        &self,
        completion_code: CompletionCode,
        dest_addr: u8,
        buf: &mut [u8],
    ) -> Result<usize, ()> {
        let command_header =
            MCTPControlMessageHeader::new(false, false, 0, CommandCode::GetMCTPVersionSupport);
        let message_header = Some(&(command_header.0[..]));
        // Return
        // Completion code
        // Version Number entry count: 1
        // Version: 1.3.1
        let message_data: [u8; 6] = [completion_code as u8, 1, 0xF1, 0xF3, 0xF1, 0x00];

        self.generate_packet_bytes(dest_addr, &message_header, &message_data, buf)
    }

    /// Lists the message types that an endpoint supports
    ///
    /// `completion_code`: Indicates the completion code we should return.
    /// `dest_addr`: The address to send the data to.
    /// `supported_msg_types`: A slice to an array of bytes listing the
    ///  supported MCTP message types, this should NOT include the control
    ///  message type (0). This implementation supports a maximum of 30
    ///  control messages.
    /// `buf`: A mutable buffer to store the request bytes.
    ///
    /// Returns the length of the response.
    pub fn get_message_type_suport(
        &self,
        completion_code: CompletionCode,
        dest_addr: u8,
        supported_msg_types: &[u8],
        buf: &mut [u8],
    ) -> Result<usize, ()> {
        let command_header =
            MCTPControlMessageHeader::new(false, false, 0, CommandCode::GetMessageTypeSupport);
        let message_header = Some(&(command_header.0[..]));
        // Return
        //  * Completion code
        //  * MCTP Message Type Count
        //  * List of Message Type numbers
        let msg_type_count = supported_msg_types.len() as usize;
        let mut message_data: [u8; 32] = [0; 32];
        message_data[0] = completion_code as u8;
        message_data[1] = msg_type_count as u8;

        if supported_msg_types.len() > 30 {
            return Err(());
        }

        for (i, d) in supported_msg_types.iter().enumerate() {
            message_data[2 + i] = *d;
        }

        self.generate_packet_bytes(
            dest_addr,
            &message_header,
            &message_data[0..(msg_type_count + 2)],
            buf,
        )
    }

    /// Used to discover an MCTP endpoint’s vendor-specific MCTP extensions and capabilities
    ///
    /// `completion_code`: Indicates the completion code we should return.
    /// `dest_addr`: The address to send the data to.
    /// `vendor_id_selector`: The vendor ID set returned.
    ///  Indicates the specific capability set requested. Indices start at
    ///  0x00 and increase monotonically by 1. If the responding endpoint has
    ///  one or more capability sets with indices greater than the requested
    ///  index, it increments the requested index by 1 and returns the
    ///  resulting value in the response message. The requesting endpoint uses
    ///  the returned value to request the next capability set.
    /// `vendor_id`: A slice to an array of bytes listing a
    ///  structured field of variable length that identifies the vendor ID
    ///  format (presently PCI or IANA) and the ID of the vendor that defined
    ///  the capability set.
    ///  This should be either 3 (PCI Vendor ID) or 5 (IANA Enterprise
    ///  Number) bytes long.
    ///  If using a 16-bit numeric value or bit field, as specified by the
    ///  vendor or organization identified by the vendor ID this should
    ///  be include in this slice, increasing the total length by 2.
    /// `buf`: A mutable buffer to store the request bytes.
    ///
    /// Returns the length of the response.
    pub fn get_vendor_defined_message_support(
        &self,
        completion_code: CompletionCode,
        dest_addr: u8,
        vendor_id_selector: u8,
        vendor_id: &[u8],
        buf: &mut [u8],
    ) -> Result<usize, ()> {
        let command_header = MCTPControlMessageHeader::new(
            false,
            false,
            0,
            CommandCode::GetVendorDefinedMessageSupport,
        );
        let message_header = Some(&(command_header.0[..]));
        // Return
        //  * Completion code
        //  * Vendor ID Set Selector
        //  * Vendor ID (variable length, between 3 and 5 bytes)
        //  * 16-bit numeric value or bit field, as specified by the vendor
        //    or organization identified by the vendor ID
        let vendor_length = vendor_id.len() as usize;
        let mut message_data: [u8; 9] = [
            completion_code as u8,
            vendor_id_selector,
            0, // Vendor ID Format
            0, // PCI Vendor ID or IANA Enterprise Number
            0, // PCI Vendor ID or IANA Enterprise Number
            0, // IANA Enterprise Number or numeric value
            0, // IANA Enterprise Number or numeric value
            0, // numeric value (IANA)
            0, // numeric value (IANA)
        ];

        for (i, d) in vendor_id.iter().enumerate() {
            message_data[2 + i] = *d;
        }

        self.generate_packet_bytes(
            dest_addr,
            &message_header,
            &message_data[0..(vendor_length + 2)],
            buf,
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::base_packet::MessageType;
    use crate::smbus_proto::{HDR_VERSION, MCTP_SMBUS_COMMAND_CODE};

    #[test]
    fn test_generate_smbus_header() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);

        let header = ctx.generate_smbus_header(DEST_ID);
        let buf = header.0;

        // Destination slave address, bit 0 is always 0.
        assert_eq!(buf[0], DEST_ID << 1);
        // Command code, is always 0x0F
        assert_eq!(buf[1], MCTP_SMBUS_COMMAND_CODE);
        // Byte count, is set later
        assert_eq!(buf[2], 0);
        // Source slave address, bit 0 is always 1
        assert_eq!(buf[3], SOURCE_ID << 1 | 1);
    }

    #[test]
    fn test_generate_transport_header() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);

        let header = ctx.generate_transport_header(DEST_ID);
        let buf = header.0;

        // HDR version and reserved field
        assert_eq!(buf[0], HDR_VERSION);
        // Destination endpoint ID
        assert_eq!(buf[1], DEST_ID);
        // Source endpoint ID
        assert_eq!(buf[2], SOURCE_ID);
        // SOM, EOM, Pck_seq, TO and Msg_tab
        assert_eq!(buf[3], 1 << 7 | 1 << 6 | 0 << 4 | 1 << 3 | 0);
    }

    #[test]
    fn test_set_endpoint_id() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;
        const EID: u8 = 0x78;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);
        let mut buf: [u8; 21] = [0; 21];

        ctx.set_eid(EID);

        let len = ctx
            .set_endpoint_id(
                CompletionCode::Success,
                DEST_ID,
                MCTPSetEndpointIDAssignmentStatus::Accpeted,
                MCTPSetEndpointIDAllocationStatus::NoIDPool,
                &mut buf,
            )
            .unwrap();

        assert_eq!(len, 16);

        // Byte count
        assert_eq!(buf[2], 12);

        // IC and Message Type
        assert_eq!(buf[8], 0 << 7 | MessageType::MCtpControl as u8);
        // Rq, D, rsvd and Instance ID
        assert_eq!(buf[9], 0 << 7 | 0 << 6 | 0 << 5 | 0);

        // Command Code
        assert_eq!(buf[10], CommandCode::SetEndpointID as u8);
        // Completion Code
        assert_eq!(buf[11], CompletionCode::Success as u8);

        // EID Status
        assert_eq!(
            buf[12],
            (MCTPSetEndpointIDAssignmentStatus::Accpeted as u8) << 4
                | MCTPSetEndpointIDAllocationStatus::NoIDPool as u8
        );
        // EID Setting
        assert_eq!(buf[13], ctx.get_eid());
        // EID Pool Size
        assert_eq!(buf[14], 0x00);
    }

    #[test]
    fn test_get_endpoint_id() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;
        const EID: u8 = 0x78;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);
        let mut buf: [u8; 21] = [0; 21];

        ctx.set_eid(EID);

        let len = ctx
            .get_endpoint_id(
                CompletionCode::Success,
                DEST_ID,
                MCTPGetEndpointIDEndpointType::Simple,
                MCTPGetEndpointIDEndpointIDType::DynamicEID,
                true,
                &mut buf,
            )
            .unwrap();

        assert_eq!(len, 16);

        // Byte count
        assert_eq!(buf[2], 12);

        // IC and Message Type
        assert_eq!(buf[8], 0 << 7 | MessageType::MCtpControl as u8);
        // Rq, D, rsvd and Instance ID
        assert_eq!(buf[9], 0 << 7 | 0 << 6 | 0 << 5 | 0);

        // Command Code
        assert_eq!(buf[10], CommandCode::GetEndpointID as u8);
        // Completion Code
        assert_eq!(buf[11], CompletionCode::Success as u8);

        // Endpoint ID
        assert_eq!(buf[12], EID);
        // Endpoint Type (Simple endpoint, Dynamic EID)
        assert_eq!(buf[13], 0);
        // Medium Specific Info
        assert_eq!(buf[14], 0x01);
    }

    #[test]
    fn test_get_endpoint_uuid() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;
        const EID: u8 = 0x78;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);
        let mut buf: [u8; 32] = [0; 32];

        ctx.set_eid(EID);

        let uuid: [u8; 16] = [
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D,
            0x0E, 0x0F,
        ];

        let len = ctx
            .get_endpoint_uuid(CompletionCode::Success, DEST_ID, &uuid, &mut buf)
            .unwrap();

        assert_eq!(len, 29);

        // Byte count
        assert_eq!(buf[2], 25);

        // IC and Message Type
        assert_eq!(buf[8], 0 << 7 | MessageType::MCtpControl as u8);
        // Rq, D, rsvd and Instance ID
        assert_eq!(buf[9], 0 << 7 | 0 << 6 | 0 << 5 | 0);

        // Command Code
        assert_eq!(buf[10], CommandCode::GetEndpointUUID as u8);
        // Completion Code
        assert_eq!(buf[11], CompletionCode::Success as u8);

        // Endpoint ID
        for (i, d) in uuid.iter().enumerate() {
            assert_eq!(buf[12 + i], *d);
        }
    }

    #[test]
    fn test_get_mctp_version_support() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);
        let mut buf: [u8; 21] = [0; 21];

        let len = ctx
            .get_mctp_version_support(CompletionCode::Success, DEST_ID, &mut buf)
            .unwrap();

        assert_eq!(len, 18);

        // Byte count
        assert_eq!(buf[2], 14);

        // IC and Message Type
        assert_eq!(buf[8], 0 << 7 | MessageType::MCtpControl as u8);
        // Rq, D, rsvd and Instance ID
        assert_eq!(buf[9], 0 << 7 | 0 << 6 | 0 << 5 | 0);

        // Command Code
        assert_eq!(buf[10], CommandCode::GetMCTPVersionSupport as u8);
        // Completion Code
        assert_eq!(buf[11], CompletionCode::Success as u8);

        // Version Entry Count
        assert_eq!(buf[12], 1);
        // Major version number
        assert_eq!(buf[13], 0xF1);
        // Major version number
        assert_eq!(buf[14], 0xF3);
        // Update version number
        assert_eq!(buf[15], 0xF1);
        // Alpha byte
        assert_eq!(buf[16], 0x00);
    }

    #[test]
    fn test_get_message_type_suport() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);
        let mut buf: [u8; 21] = [0; 21];

        let msg_types = [0x7E];

        let len = ctx
            .get_message_type_suport(CompletionCode::Success, DEST_ID, &msg_types, &mut buf)
            .unwrap();

        assert_eq!(len, 15);

        // Byte count
        assert_eq!(buf[2], 11);

        // IC and Message Type
        assert_eq!(buf[8], 0 << 7 | MessageType::MCtpControl as u8);
        // Rq, D, rsvd and Instance ID
        assert_eq!(buf[9], 0 << 7 | 0 << 6 | 0 << 5 | 0);

        // Command Code
        assert_eq!(buf[10], CommandCode::GetMessageTypeSupport as u8);
        // Completion Code
        assert_eq!(buf[11], CompletionCode::Success as u8);

        // Version Entry Count
        assert_eq!(buf[12], msg_types.len() as u8);
        assert_eq!(buf[13], msg_types[0]);
    }

    #[test]
    fn test_get_vendor_defined_message_support() {
        const DEST_ID: u8 = 0x23;
        const SOURCE_ID: u8 = 0x23;

        let ctx = MCTPSMBusContextResponse::new(SOURCE_ID);
        let mut buf: [u8; 21] = [0; 21];

        let vendor_id = [
            0x00, // PCI Vendor
            0xAB, 0xBC, 0x12, 0x34,
        ];

        let len = ctx
            .get_vendor_defined_message_support(
                CompletionCode::Success,
                DEST_ID,
                0xFF,
                &vendor_id,
                &mut buf,
            )
            .unwrap();

        assert_eq!(len, 19);

        // Byte count
        assert_eq!(buf[2], 15);

        // IC and Message Type
        assert_eq!(buf[8], 0 << 7 | MessageType::MCtpControl as u8);
        // Rq, D, rsvd and Instance ID
        assert_eq!(buf[9], 0 << 7 | 0 << 6 | 0 << 5 | 0);

        // Command Code
        assert_eq!(buf[10], CommandCode::GetVendorDefinedMessageSupport as u8);
        // Completion Code
        assert_eq!(buf[11], CompletionCode::Success as u8);

        // Vendor ID Set Selector
        assert_eq!(buf[12], 0xFF);

        // Vendor ID
        for (i, d) in vendor_id.iter().enumerate() {
            assert_eq!(buf[13 + i], *d);
        }
    }
}