vhu_i2c.rs 26.1 KB
Newer Older
Viresh Kumar's avatar
Viresh Kumar committed
1 2 3 4 5 6 7
// vhost device i2c
//
// Copyright 2021 Linaro Ltd. All Rights Reserved.
//          Viresh Kumar <viresh.kumar@linaro.org>
//
// SPDX-License-Identifier: Apache-2.0

8
use log::warn;
Viresh Kumar's avatar
Viresh Kumar committed
9
use std::mem::size_of;
10
use std::sync::Arc;
Viresh Kumar's avatar
Viresh Kumar committed
11
use std::{convert, io};
Viresh Kumar's avatar
Viresh Kumar committed
12

Viresh Kumar's avatar
Viresh Kumar committed
13
use thiserror::Error as ThisError;
Viresh Kumar's avatar
Viresh Kumar committed
14
use vhost::vhost_user::message::{VhostUserProtocolFeatures, VhostUserVirtioFeatures};
15
use vhost_user_backend::{VhostUserBackendMut, VringRwLock, VringT};
Viresh Kumar's avatar
Viresh Kumar committed
16 17 18 19
use virtio_bindings::bindings::virtio_net::{VIRTIO_F_NOTIFY_ON_EMPTY, VIRTIO_F_VERSION_1};
use virtio_bindings::bindings::virtio_ring::{
    VIRTIO_RING_F_EVENT_IDX, VIRTIO_RING_F_INDIRECT_DESC,
};
20
use virtio_queue::DescriptorChain;
21 22 23
use vm_memory::{
    ByteValued, Bytes, GuestMemoryAtomic, GuestMemoryLoadGuard, GuestMemoryMmap, Le16, Le32,
};
24
use vmm_sys_util::epoll::EventSet;
Viresh Kumar's avatar
Viresh Kumar committed
25 26
use vmm_sys_util::eventfd::{EventFd, EFD_NONBLOCK};

Viresh Kumar's avatar
Viresh Kumar committed
27 28
use crate::i2c::*;

29 30 31
/// Virtio I2C Feature bits
const VIRTIO_I2C_F_ZERO_LENGTH_REQUEST: u16 = 0;

Viresh Kumar's avatar
Viresh Kumar committed
32 33 34 35 36 37
const QUEUE_SIZE: usize = 1024;
const NUM_QUEUES: usize = 1;

type Result<T> = std::result::Result<T, Error>;
type VhostUserBackendResult<T> = std::result::Result<T, std::io::Error>;

38
#[derive(Copy, Clone, Debug, PartialEq, ThisError)]
Viresh Kumar's avatar
Viresh Kumar committed
39 40
/// Errors related to vhost-device-i2c daemon.
pub enum Error {
Viresh Kumar's avatar
Viresh Kumar committed
41
    #[error("Failed to handle event, didn't match EPOLLIN")]
Viresh Kumar's avatar
Viresh Kumar committed
42
    HandleEventNotEpollIn,
Viresh Kumar's avatar
Viresh Kumar committed
43 44
    #[error("Failed to handle unknown event")]
    HandleEventUnknown,
45 46 47 48 49 50 51 52
    #[error("Received unexpected write only descriptor at index {0}")]
    UnexpectedWriteOnlyDescriptor(usize),
    #[error("Received unexpected readable descriptor at index {0}")]
    UnexpectedReadableDescriptor(usize),
    #[error("Invalid descriptor count {0}")]
    UnexpectedDescriptorCount(usize),
    #[error("Invalid descriptor size, expected: {0}, found: {1}")]
    UnexpectedDescriptorSize(usize, u32),
Viresh Kumar's avatar
Viresh Kumar committed
53
    #[error("Descriptor not found")]
Viresh Kumar's avatar
Viresh Kumar committed
54
    DescriptorNotFound,
Viresh Kumar's avatar
Viresh Kumar committed
55
    #[error("Descriptor read failed")]
Viresh Kumar's avatar
Viresh Kumar committed
56
    DescriptorReadFailed,
Viresh Kumar's avatar
Viresh Kumar committed
57
    #[error("Descriptor write failed")]
Viresh Kumar's avatar
Viresh Kumar committed
58
    DescriptorWriteFailed,
Viresh Kumar's avatar
Viresh Kumar committed
59 60
    #[error("Failed to send notification")]
    NotificationFailed,
61 62
    #[error("Failed to create new EventFd")]
    EventFdFailed,
Viresh Kumar's avatar
Viresh Kumar committed
63 64 65 66 67 68 69 70
}

impl convert::From<Error> for io::Error {
    fn from(e: Error) -> Self {
        io::Error::new(io::ErrorKind::Other, e)
    }
}

Viresh Kumar's avatar
Viresh Kumar committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
/// I2C definitions from Virtio Spec

/// The final status written by the device
const VIRTIO_I2C_MSG_OK: u8 = 0;
const VIRTIO_I2C_MSG_ERR: u8 = 1;

#[derive(Copy, Clone, Default)]
#[repr(C)]
struct VirtioI2cOutHdr {
    addr: Le16,
    padding: Le16,
    flags: Le32,
}
unsafe impl ByteValued for VirtioI2cOutHdr {}

86 87 88
/// VirtioI2cOutHdr Flags
const VIRTIO_I2C_FLAGS_M_RD: u32 = 1 << 1;

Viresh Kumar's avatar
Viresh Kumar committed
89 90 91 92 93 94 95
#[derive(Copy, Clone, Default)]
#[repr(C)]
struct VirtioI2cInHdr {
    status: u8,
}
unsafe impl ByteValued for VirtioI2cInHdr {}

96 97
pub struct VhostUserI2cBackend<D: I2cDevice> {
    i2c_map: Arc<I2cMap<D>>,
Viresh Kumar's avatar
Viresh Kumar committed
98 99 100 101
    event_idx: bool,
    pub exit_event: EventFd,
}

102
type I2cDescriptorChain = DescriptorChain<GuestMemoryLoadGuard<GuestMemoryMmap<()>>>;
Viresh Kumar's avatar
Viresh Kumar committed
103

104 105 106 107 108 109 110
impl<D: I2cDevice> VhostUserI2cBackend<D> {
    pub fn new(i2c_map: Arc<I2cMap<D>>) -> Result<Self> {
        Ok(VhostUserI2cBackend {
            i2c_map,
            event_idx: false,
            exit_event: EventFd::new(EFD_NONBLOCK).map_err(|_| Error::EventFdFailed)?,
        })
111 112
    }

113 114 115 116
    /// Process the requests in the vring and dispatch replies
    fn process_requests(
        &self,
        requests: Vec<I2cDescriptorChain>,
117
        vring: &VringRwLock,
118 119 120 121 122
    ) -> Result<bool> {
        let mut reqs: Vec<I2cReq> = Vec::new();

        if requests.is_empty() {
            return Ok(true);
Viresh Kumar's avatar
Viresh Kumar committed
123 124
        }

125 126 127
        // Iterate over each I2C request and push it to "reqs" vector.
        for desc_chain in requests.clone() {
            let descriptors: Vec<_> = desc_chain.clone().collect();
Viresh Kumar's avatar
Viresh Kumar committed
128

129 130 131
            if (descriptors.len() != 2) && (descriptors.len() != 3) {
                return Err(Error::UnexpectedDescriptorCount(descriptors.len()));
            }
Viresh Kumar's avatar
Viresh Kumar committed
132

133
            let desc_out_hdr = descriptors[0];
Viresh Kumar's avatar
Viresh Kumar committed
134

135 136 137
            if desc_out_hdr.is_write_only() {
                return Err(Error::UnexpectedWriteOnlyDescriptor(0));
            }
Viresh Kumar's avatar
Viresh Kumar committed
138

139 140 141 142 143 144
            if desc_out_hdr.len() as usize != size_of::<VirtioI2cOutHdr>() {
                return Err(Error::UnexpectedDescriptorSize(
                    size_of::<VirtioI2cOutHdr>(),
                    desc_out_hdr.len(),
                ));
            }
145

146 147 148 149
            let out_hdr = desc_chain
                .memory()
                .read_obj::<VirtioI2cOutHdr>(desc_out_hdr.addr())
                .map_err(|_| Error::DescriptorReadFailed)?;
Viresh Kumar's avatar
Viresh Kumar committed
150

151 152 153 154
            let flags = match out_hdr.flags.to_native() & VIRTIO_I2C_FLAGS_M_RD {
                VIRTIO_I2C_FLAGS_M_RD => I2C_M_RD,
                _ => 0,
            };
Viresh Kumar's avatar
Viresh Kumar committed
155

156 157 158 159
            let desc_in_hdr = descriptors[descriptors.len() - 1];
            if !desc_in_hdr.is_write_only() {
                return Err(Error::UnexpectedReadableDescriptor(descriptors.len() - 1));
            }
Viresh Kumar's avatar
Viresh Kumar committed
160

161 162 163 164 165 166 167 168 169 170 171 172
            if desc_in_hdr.len() as usize != size_of::<u8>() {
                return Err(Error::UnexpectedDescriptorSize(
                    size_of::<u8>(),
                    desc_in_hdr.len(),
                ));
            }

            let (buf, len) = match descriptors.len() {
                // Buffer is available
                3 => {
                    let desc_buf = descriptors[1];
                    let len = desc_buf.len();
Viresh Kumar's avatar
Viresh Kumar committed
173

174 175
                    if len == 0 {
                        return Err(Error::UnexpectedDescriptorSize(1, len));
176
                    }
177
                    let mut buf = vec![0; len as usize];
178

179 180 181 182
                    if flags != I2C_M_RD {
                        if desc_buf.is_write_only() {
                            return Err(Error::UnexpectedWriteOnlyDescriptor(1));
                        }
183

184 185 186 187 188 189 190
                        desc_chain
                            .memory()
                            .read(&mut buf, desc_buf.addr())
                            .map_err(|_| Error::DescriptorReadFailed)?;
                    } else if !desc_buf.is_write_only() {
                        return Err(Error::UnexpectedReadableDescriptor(1));
                    }
Viresh Kumar's avatar
Viresh Kumar committed
191

192 193
                    (buf, len)
                }
Viresh Kumar's avatar
Viresh Kumar committed
194

195 196
                _ => (Vec::<u8>::new(), 0),
            };
197

198 199 200 201 202 203
            reqs.push(I2cReq {
                addr: out_hdr.addr.to_native() >> 1,
                flags,
                len: len as u16,
                buf,
            });
204 205
        }

206 207 208 209 210 211 212 213
        let in_hdr = {
            VirtioI2cInHdr {
                status: match self.i2c_map.transfer(&mut reqs) {
                    Ok(()) => VIRTIO_I2C_MSG_OK,
                    Err(_) => VIRTIO_I2C_MSG_ERR,
                },
            }
        };
214

215 216 217 218
        for (i, desc_chain) in requests.iter().enumerate() {
            let descriptors: Vec<_> = desc_chain.clone().collect();
            let desc_in_hdr = descriptors[descriptors.len() - 1];
            let mut len = size_of::<VirtioI2cInHdr>() as u32;
219

220 221 222 223 224 225 226 227 228 229
            if descriptors.len() == 3 {
                let desc_buf = descriptors[1];

                // Write the data read from the I2C device
                if reqs[i].flags == I2C_M_RD {
                    desc_chain
                        .memory()
                        .write(&reqs[i].buf, desc_buf.addr())
                        .map_err(|_| Error::DescriptorWriteFailed)?;
                }
230

231 232 233
                if in_hdr.status == VIRTIO_I2C_MSG_OK {
                    len += desc_buf.len();
                }
Viresh Kumar's avatar
Viresh Kumar committed
234 235
            }

236 237 238 239 240
            // Write the transfer status
            desc_chain
                .memory()
                .write_obj::<VirtioI2cInHdr>(in_hdr, desc_in_hdr.addr())
                .map_err(|_| Error::DescriptorWriteFailed)?;
Viresh Kumar's avatar
Viresh Kumar committed
241

242 243
            if vring.add_used(desc_chain.head_index(), len).is_err() {
                warn!("Couldn't return used descriptors to the ring");
Viresh Kumar's avatar
Viresh Kumar committed
244 245
            }
        }
246

247
        Ok(true)
248 249 250 251 252 253 254 255 256 257 258
    }

    /// Process the requests in the vring and dispatch replies
    fn process_queue(&self, vring: &VringRwLock) -> Result<bool> {
        let requests: Vec<_> = vring
            .get_mut()
            .get_queue_mut()
            .iter()
            .map_err(|_| Error::DescriptorNotFound)?
            .collect();

259
        if self.process_requests(requests, vring)? {
260 261 262 263 264
            // Send notification once all the requests are processed
            vring
                .signal_used_queue()
                .map_err(|_| Error::NotificationFailed)?;
        }
Viresh Kumar's avatar
Viresh Kumar committed
265

Viresh Kumar's avatar
Viresh Kumar committed
266 267 268 269
        Ok(true)
    }
}

270
/// VhostUserBackendMut trait methods
Andreea Florescu's avatar
Andreea Florescu committed
271 272 273
impl<D: 'static + I2cDevice + Sync + Send> VhostUserBackendMut<VringRwLock, ()>
    for VhostUserI2cBackend<D>
{
Viresh Kumar's avatar
Viresh Kumar committed
274 275 276 277 278 279 280 281 282 283 284 285 286 287
    fn num_queues(&self) -> usize {
        NUM_QUEUES
    }

    fn max_queue_size(&self) -> usize {
        QUEUE_SIZE
    }

    fn features(&self) -> u64 {
        // this matches the current libvhost defaults except VHOST_F_LOG_ALL
        1 << VIRTIO_F_VERSION_1
            | 1 << VIRTIO_F_NOTIFY_ON_EMPTY
            | 1 << VIRTIO_RING_F_INDIRECT_DESC
            | 1 << VIRTIO_RING_F_EVENT_IDX
288
            | 1 << VIRTIO_I2C_F_ZERO_LENGTH_REQUEST
Viresh Kumar's avatar
Viresh Kumar committed
289 290 291 292 293 294 295 296 297 298 299 300 301
            | VhostUserVirtioFeatures::PROTOCOL_FEATURES.bits()
    }

    fn protocol_features(&self) -> VhostUserProtocolFeatures {
        VhostUserProtocolFeatures::MQ
    }

    fn set_event_idx(&mut self, enabled: bool) {
        dbg!(self.event_idx = enabled);
    }

    fn update_memory(
        &mut self,
Viresh Kumar's avatar
Viresh Kumar committed
302
        _mem: GuestMemoryAtomic<GuestMemoryMmap>,
Viresh Kumar's avatar
Viresh Kumar committed
303 304 305 306 307
    ) -> VhostUserBackendResult<()> {
        Ok(())
    }

    fn handle_event(
308
        &mut self,
Viresh Kumar's avatar
Viresh Kumar committed
309
        device_event: u16,
310
        evset: EventSet,
311
        vrings: &[VringRwLock],
Viresh Kumar's avatar
Viresh Kumar committed
312 313
        _thread_id: usize,
    ) -> VhostUserBackendResult<bool> {
314
        if evset != EventSet::IN {
Viresh Kumar's avatar
Viresh Kumar committed
315 316 317 318 319
            return Err(Error::HandleEventNotEpollIn.into());
        }

        match device_event {
            0 => {
320
                let vring = &vrings[0];
Viresh Kumar's avatar
Viresh Kumar committed
321 322 323 324 325 326 327

                if self.event_idx {
                    // vm-virtio's Queue implementation only checks avail_index
                    // once, so to properly support EVENT_IDX we need to keep
                    // calling process_queue() until it stops finding new
                    // requests on the queue.
                    loop {
328 329 330
                        vring.disable_notification().unwrap();
                        self.process_queue(vring)?;
                        if !vring.enable_notification().unwrap() {
Viresh Kumar's avatar
Viresh Kumar committed
331 332 333 334 335
                            break;
                        }
                    }
                } else {
                    // Without EVENT_IDX, a single call is enough.
336
                    self.process_queue(vring)?;
Viresh Kumar's avatar
Viresh Kumar committed
337 338 339 340
                }
            }

            _ => {
341
                warn!("unhandled device_event: {}", device_event);
Viresh Kumar's avatar
Viresh Kumar committed
342
                return Err(Error::HandleEventUnknown.into());
Viresh Kumar's avatar
Viresh Kumar committed
343 344 345 346 347
            }
        }
        Ok(false)
    }

348
    fn exit_event(&self, _thread_index: usize) -> Option<EventFd> {
Viresh Kumar's avatar
Viresh Kumar committed
349
        self.exit_event.try_clone().ok()
Viresh Kumar's avatar
Viresh Kumar committed
350 351
    }
}
352 353 354

#[cfg(test)]
mod tests {
355 356 357 358 359 360 361
    use std::convert::TryFrom;

    use virtio_queue::defs::{VIRTQ_DESC_F_NEXT, VIRTQ_DESC_F_WRITE};
    use virtio_queue::{mock::MockSplitQueue, Descriptor};
    use vm_memory::{Address, GuestAddress, GuestMemoryAtomic, GuestMemoryMmap};

    use super::Error;
362
    use super::*;
363
    use crate::i2c::tests::{update_rdwr_buf, verify_rdwr_buf, DummyDevice};
Viresh Kumar's avatar
Viresh Kumar committed
364
    use crate::AdapterConfig;
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

    // Prepares a single chain of descriptors
    fn prepare_desc_chain(
        start_addr: GuestAddress,
        buf: &mut Vec<u8>,
        flag: u32,
        client_addr: u16,
    ) -> I2cDescriptorChain {
        let mem = GuestMemoryMmap::<()>::from_ranges(&[(start_addr, 0x1000)]).unwrap();
        let vq = MockSplitQueue::new(&mem, 16);
        let mut next_addr = vq.desc_table().total_size() + 0x100;
        let mut index = 0;

        // Out header descriptor
        let out_hdr = VirtioI2cOutHdr {
            addr: From::from(client_addr << 1),
            padding: From::from(0x0),
            flags: From::from(flag),
        };

        let desc_out = Descriptor::new(
            next_addr,
            size_of::<VirtioI2cOutHdr>() as u32,
            VIRTQ_DESC_F_NEXT,
            index + 1,
        );

        mem.write_obj::<VirtioI2cOutHdr>(out_hdr, desc_out.addr())
            .unwrap();
        vq.desc_table().store(index, desc_out);
        next_addr += desc_out.len() as u64;
        index += 1;

        // Buf descriptor: optional
        if !buf.is_empty() {
            // Set buffer is write-only or not
            let flag = if (flag & VIRTIO_I2C_FLAGS_M_RD) == 0 {
                update_rdwr_buf(buf);
                0
            } else {
                VIRTQ_DESC_F_WRITE
            };

            let desc_buf = Descriptor::new(
                next_addr,
                buf.len() as u32,
                flag | VIRTQ_DESC_F_NEXT,
                index + 1,
            );
            mem.write(buf, desc_buf.addr()).unwrap();
            vq.desc_table().store(index, desc_buf);
            next_addr += desc_buf.len() as u64;
            index += 1;
        }

        // In response descriptor
        let desc_in = Descriptor::new(next_addr, size_of::<u8>() as u32, VIRTQ_DESC_F_WRITE, 0);
        vq.desc_table().store(index, desc_in);

        // Put the descriptor index 0 in the first available ring position.
        mem.write_obj(0u16, vq.avail_addr().unchecked_add(4))
            .unwrap();

        // Set `avail_idx` to 1.
        mem.write_obj(1u16, vq.avail_addr().unchecked_add(2))
            .unwrap();

        // Create descriptor chain from pre-filled memory
        vq.create_queue(GuestMemoryAtomic::<GuestMemoryMmap>::new(mem.clone()))
            .iter()
            .unwrap()
            .next()
            .unwrap()
    }

    // Validate descriptor chains after processing them, checks pass/failure of
    // operation and the value of the buffers updated by the `DummyDevice`.
    fn validate_desc_chains(desc_chains: Vec<I2cDescriptorChain>, status: u8) {
        for desc_chain in desc_chains {
            let descriptors: Vec<_> = desc_chain.clone().collect();

            let in_hdr = desc_chain
                .memory()
                .read_obj::<VirtioI2cInHdr>(descriptors[descriptors.len() - 1].addr())
                .unwrap();

            // Operation result should match expected status.
            assert_eq!(in_hdr.status, status);

            let out_hdr = desc_chain
                .memory()
                .read_obj::<VirtioI2cOutHdr>(descriptors[0].addr())
                .unwrap();

            if (out_hdr.flags.to_native() & VIRTIO_I2C_FLAGS_M_RD) != 0 && descriptors.len() == 3 {
                let mut buf = vec![0; descriptors[1].len() as usize];
                desc_chain
                    .memory()
                    .read(&mut buf, descriptors[1].addr())
                    .unwrap();

                // Verify the content of the read-buffer
                verify_rdwr_buf(&buf);
            }
        }
    }

    // Prepares list of dummy descriptors, their content isn't significant
    fn prepare_desc_chain_dummy(
        addr: Option<Vec<u64>>,
        flags: Vec<u16>,
        len: Vec<u32>,
    ) -> I2cDescriptorChain {
        let mem = GuestMemoryMmap::<()>::from_ranges(&[(GuestAddress(0), 0x1000)]).unwrap();
        let vq = MockSplitQueue::new(&mem, 16);

        for (i, flag) in flags.iter().enumerate() {
            let mut f = if i == flags.len() - 1 {
                0
            } else {
                VIRTQ_DESC_F_NEXT
            };
            f |= flag;

            let offset = match addr {
                Some(ref addr) => addr[i],
                _ => 0x100,
            };

            let desc = Descriptor::new(offset, len[i], f, (i + 1) as u16);
            vq.desc_table().store(i as u16, desc);
        }

        // Put the descriptor index 0 in the first available ring position.
        mem.write_obj(0u16, vq.avail_addr().unchecked_add(4))
            .unwrap();

        // Set `avail_idx` to 1.
        mem.write_obj(1u16, vq.avail_addr().unchecked_add(2))
            .unwrap();

        // Create descriptor chain from pre-filled memory
        vq.create_queue(GuestMemoryAtomic::<GuestMemoryMmap>::new(mem.clone()))
            .iter()
            .unwrap()
            .next()
            .unwrap()
    }

    #[test]
    fn process_requests_success() {
        let device_config = AdapterConfig::try_from("1:4,2:32:21,5:10:23").unwrap();
517 518
        let i2c_map = I2cMap::<DummyDevice>::new(&device_config).unwrap();
        let backend = VhostUserI2cBackend::new(Arc::new(i2c_map)).unwrap();
519 520 521 522
        let mem = GuestMemoryAtomic::new(
            GuestMemoryMmap::<()>::from_ranges(&[(GuestAddress(0), 0x1000)]).unwrap(),
        );
        let vring = VringRwLock::new(mem, 0x1000);
523 524

        // Descriptor chain size zero, shouldn't fail
525
        backend
526
            .process_requests(Vec::<I2cDescriptorChain>::new(), &vring)
527
            .unwrap();
528 529 530 531 532 533

        // Valid single read descriptor
        let mut buf: Vec<u8> = vec![0; 30];
        let desc_chain = prepare_desc_chain(GuestAddress(0), &mut buf, VIRTIO_I2C_FLAGS_M_RD, 4);
        let desc_chains = vec![desc_chain];

534 535 536
        backend
            .process_requests(desc_chains.clone(), &vring)
            .unwrap();
537 538 539 540 541 542 543
        validate_desc_chains(desc_chains, VIRTIO_I2C_MSG_OK);

        // Valid single write descriptor
        let mut buf: Vec<u8> = vec![0; 30];
        let desc_chain = prepare_desc_chain(GuestAddress(0), &mut buf, 0, 4);
        let desc_chains = vec![desc_chain];

544 545 546
        backend
            .process_requests(desc_chains.clone(), &vring)
            .unwrap();
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
        validate_desc_chains(desc_chains, VIRTIO_I2C_MSG_OK);

        // Valid mixed read-write descriptors
        let mut buf: Vec<Vec<u8>> = vec![vec![0; 30]; 6];
        let desc_chains = vec![
            // Write
            prepare_desc_chain(GuestAddress(0), &mut buf[0], 0, 4),
            // Read
            prepare_desc_chain(GuestAddress(0), &mut buf[1], VIRTIO_I2C_FLAGS_M_RD, 4),
            // Write
            prepare_desc_chain(GuestAddress(0), &mut buf[2], 0, 4),
            // Read
            prepare_desc_chain(GuestAddress(0), &mut buf[3], VIRTIO_I2C_FLAGS_M_RD, 4),
            // Write
            prepare_desc_chain(GuestAddress(0), &mut buf[4], 0, 4),
            // Read
            prepare_desc_chain(GuestAddress(0), &mut buf[5], VIRTIO_I2C_FLAGS_M_RD, 4),
        ];

566 567 568
        backend
            .process_requests(desc_chains.clone(), &vring)
            .unwrap();
569 570 571 572 573 574
        validate_desc_chains(desc_chains, VIRTIO_I2C_MSG_OK);
    }

    #[test]
    fn process_requests_failure() {
        let device_config = AdapterConfig::try_from("1:4,2:32:21,5:10:23").unwrap();
575 576
        let i2c_map = I2cMap::<DummyDevice>::new(&device_config).unwrap();
        let backend = VhostUserI2cBackend::new(Arc::new(i2c_map)).unwrap();
577 578 579 580
        let mem = GuestMemoryAtomic::new(
            GuestMemoryMmap::<()>::from_ranges(&[(GuestAddress(0), 0x1000)]).unwrap(),
        );
        let vring = VringRwLock::new(mem, 0x1000);
581 582 583 584 585 586

        // One descriptors
        let flags: Vec<u16> = vec![0];
        let len: Vec<u32> = vec![0];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
587
            backend
588
                .process_requests(vec![desc_chain], &vring)
589
                .unwrap_err(),
590 591 592 593 594 595 596 597
            Error::UnexpectedDescriptorCount(1)
        );

        // Four descriptors
        let flags: Vec<u16> = vec![0, 0, 0, 0];
        let len: Vec<u32> = vec![0, 0, 0, 0];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
598
            backend
599
                .process_requests(vec![desc_chain], &vring)
600
                .unwrap_err(),
601 602 603 604 605 606 607 608 609 610 611 612
            Error::UnexpectedDescriptorCount(4)
        );

        // Write only out hdr
        let flags: Vec<u16> = vec![VIRTQ_DESC_F_WRITE, 0, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![
            size_of::<VirtioI2cOutHdr>() as u32,
            1,
            size_of::<u8>() as u32,
        ];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
613
            backend
614
                .process_requests(vec![desc_chain], &vring)
615
                .unwrap_err(),
616 617 618 619 620 621 622 623
            Error::UnexpectedWriteOnlyDescriptor(0)
        );

        // Invalid out hdr length
        let flags: Vec<u16> = vec![0, 0, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![100, 1, size_of::<u8>() as u32];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
624
            backend
625
                .process_requests(vec![desc_chain], &vring)
626
                .unwrap_err(),
627 628 629 630 631 632 633 634 635 636 637 638 639
            Error::UnexpectedDescriptorSize(size_of::<VirtioI2cOutHdr>(), 100)
        );

        // Invalid out hdr address
        let addr: Vec<u64> = vec![0x10000, 0, 0];
        let flags: Vec<u16> = vec![0, 0, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![
            size_of::<VirtioI2cOutHdr>() as u32,
            1,
            size_of::<u8>() as u32,
        ];
        let desc_chain = prepare_desc_chain_dummy(Some(addr), flags, len);
        assert_eq!(
640
            backend
641
                .process_requests(vec![desc_chain], &vring)
642
                .unwrap_err(),
643 644 645 646 647 648 649 650 651 652 653 654
            Error::DescriptorReadFailed
        );

        // Read only in hdr
        let flags: Vec<u16> = vec![0, 0, 0];
        let len: Vec<u32> = vec![
            size_of::<VirtioI2cOutHdr>() as u32,
            1,
            size_of::<u8>() as u32,
        ];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
655
            backend
656
                .process_requests(vec![desc_chain], &vring)
657
                .unwrap_err(),
658 659 660 661 662 663 664 665
            Error::UnexpectedReadableDescriptor(2)
        );

        // Invalid in hdr length
        let flags: Vec<u16> = vec![0, 0, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![size_of::<VirtioI2cOutHdr>() as u32, 1, 100];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
666
            backend
667
                .process_requests(vec![desc_chain], &vring)
668
                .unwrap_err(),
669 670 671 672 673 674 675 676 677 678 679 680 681
            Error::UnexpectedDescriptorSize(size_of::<u8>(), 100)
        );

        // Invalid in hdr address
        let addr: Vec<u64> = vec![0, 0, 0x10000];
        let flags: Vec<u16> = vec![0, 0, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![
            size_of::<VirtioI2cOutHdr>() as u32,
            1,
            size_of::<u8>() as u32,
        ];
        let desc_chain = prepare_desc_chain_dummy(Some(addr), flags, len);
        assert_eq!(
682
            backend
683
                .process_requests(vec![desc_chain], &vring)
684
                .unwrap_err(),
685 686 687 688 689 690 691 692 693 694 695 696
            Error::DescriptorWriteFailed
        );

        // Invalid buf length
        let flags: Vec<u16> = vec![0, 0, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![
            size_of::<VirtioI2cOutHdr>() as u32,
            0,
            size_of::<u8>() as u32,
        ];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
697
            backend
698
                .process_requests(vec![desc_chain], &vring)
699
                .unwrap_err(),
700 701 702 703 704 705 706 707 708 709 710 711 712
            Error::UnexpectedDescriptorSize(1, 0)
        );

        // Invalid buf address
        let addr: Vec<u64> = vec![0, 0x10000, 0];
        let flags: Vec<u16> = vec![0, 0, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![
            size_of::<VirtioI2cOutHdr>() as u32,
            1,
            size_of::<u8>() as u32,
        ];
        let desc_chain = prepare_desc_chain_dummy(Some(addr), flags, len);
        assert_eq!(
713
            backend
714
                .process_requests(vec![desc_chain], &vring)
715
                .unwrap_err(),
716 717 718
            Error::DescriptorReadFailed
        );

Viresh Kumar's avatar
Viresh Kumar committed
719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
        // Write only buf for write operation
        let flags: Vec<u16> = vec![0, VIRTQ_DESC_F_WRITE, VIRTQ_DESC_F_WRITE];
        let len: Vec<u32> = vec![
            size_of::<VirtioI2cOutHdr>() as u32,
            10,
            size_of::<u8>() as u32,
        ];
        let desc_chain = prepare_desc_chain_dummy(None, flags, len);
        assert_eq!(
            backend
                .process_requests(vec![desc_chain], &vring)
                .unwrap_err(),
            Error::UnexpectedWriteOnlyDescriptor(1)
        );

734 735 736 737 738
        // Missing buffer for I2C rdwr transfer
        let mut buf = Vec::<u8>::new();
        let desc_chain = prepare_desc_chain(GuestAddress(0), &mut buf, VIRTIO_I2C_FLAGS_M_RD, 4);
        let desc_chains = vec![desc_chain];

739 740 741
        backend
            .process_requests(desc_chains.clone(), &vring)
            .unwrap();
742 743
        validate_desc_chains(desc_chains, VIRTIO_I2C_MSG_ERR);
    }
744 745 746

    #[test]
    fn verify_backend() {
747 748
        let device_config = AdapterConfig::try_from("1:4,2:32:21,5:10:23").unwrap();
        let i2c_map: I2cMap<DummyDevice> = I2cMap::new(&device_config).unwrap();
749 750 751 752
        let mut backend = VhostUserI2cBackend::new(Arc::new(i2c_map)).unwrap();

        assert_eq!(backend.num_queues(), NUM_QUEUES);
        assert_eq!(backend.max_queue_size(), QUEUE_SIZE);
753
        assert_eq!(backend.features(), 0x171000001);
754 755 756 757 758 759 760
        assert_eq!(backend.protocol_features(), VhostUserProtocolFeatures::MQ);

        assert_eq!(backend.queues_per_thread(), vec![0xffff_ffff]);
        assert_eq!(backend.get_config(0, 0), vec![]);

        backend.set_event_idx(true);
        assert!(backend.event_idx);
Viresh Kumar's avatar
Viresh Kumar committed
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

        assert!(backend.exit_event(0).is_some());

        let mem = GuestMemoryAtomic::new(
            GuestMemoryMmap::<()>::from_ranges(&[(GuestAddress(0), 0x1000)]).unwrap(),
        );
        backend.update_memory(mem.clone()).unwrap();

        let vring = VringRwLock::new(mem, 0x1000);
        assert_eq!(
            backend
                .handle_event(0, EventSet::OUT, &[vring.clone()], 0)
                .unwrap_err()
                .kind(),
            io::ErrorKind::Other
        );

        assert_eq!(
            backend
                .handle_event(1, EventSet::IN, &[vring.clone()], 0)
                .unwrap_err()
                .kind(),
            io::ErrorKind::Other
        );

        // Hit the loop part
        backend.set_event_idx(true);
        backend
            .handle_event(0, EventSet::IN, &[vring.clone()], 0)
            .unwrap();

        // Hit the non-loop part
        backend.set_event_idx(false);
        backend.handle_event(0, EventSet::IN, &[vring], 0).unwrap();
795
    }
796
}