1 // Copyright 2018 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #pragma once
6 
7 #include <threads.h>
8 
9 #include <ddk/driver.h>
10 #include <ddktl/protocol/i2cimpl.h>
11 #include <fbl/mutex.h>
12 #include <lib/sync/completion.h>
13 
14 #include "proxy-protocol.h"
15 
16 namespace platform_bus {
17 
18 class PlatformI2cBus {
19 public:
20     explicit PlatformI2cBus(const i2c_impl_protocol_t* i2c, uint32_t bus_id);
21     zx_status_t Start();
22 
23     zx_status_t Transact(uint32_t txid, rpc_i2c_req_t* req, uint16_t address,
24                          zx_handle_t channel_handle);
25 
26 private:
27     // struct representing an I2C transaction.
28     struct I2cTxn {
29         uint32_t txid;
30         zx_handle_t channel_handle;
31 
32         list_node_t node;
33         uint16_t address;
34         i2c_transact_callback transact_cb;
35         void* cookie;
36         size_t length;
37         size_t cnt;
38     };
39 
40     void Complete(I2cTxn* txn, zx_status_t status, const uint8_t* data,
41                   size_t data_length);
42     int I2cThread();
43 
44     ddk::I2cImplProtocolClient i2c_;
45     const uint32_t bus_id_;
46     size_t max_transfer_;
47 
48     list_node_t queued_txns_ __TA_GUARDED(mutex_);
49     list_node_t free_txns_ __TA_GUARDED(mutex_);
50     sync_completion_t txn_signal_;
51 
52     thrd_t thread_;
53     fbl::Mutex mutex_;
54 };
55 
56 } // namespace platform_bus
57