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
use std::{
    future::Future,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
};

use twizzler_object::{ObjID, Object, ObjectInitFlags, Protections};
use twizzler_queue::{CallbackQueueReceiver, QueueBase, QueueError, QueueSender, SubmissionFlags};

#[cfg(feature = "manager")]
use crate::server_rendezvous;
use crate::{
    buffer::{BufferBase, BufferController, ManagedBuffer},
    client_rendezvous,
    req::PacketData,
    rx_req::{RxCompletion, RxRequest},
    tx_req::{TxCompletion, TxRequest},
};

struct NmHandleObjects {
    tx_queue: Object<QueueBase<TxRequest, TxCompletion>>,
    rx_queue: Object<QueueBase<RxRequest, RxCompletion>>,
    #[allow(dead_code)]
    tx_buf: Object<BufferBase>,
    #[allow(dead_code)]
    rx_buf: Object<BufferBase>,
}

const DEAD: u64 = 1;
const CLOSED: u64 = 2;

pub struct NmHandle {
    _objs: NmHandleObjects,
    handler: CallbackQueueReceiver<RxRequest, RxCompletion>,
    sender: QueueSender<TxRequest, TxCompletion>,
    tx_bc: BufferController,
    rx_bc: BufferController,
    flags: AtomicU64,
    client_name: String,
    client_id: u64,
}

#[cfg(feature = "manager")]
pub struct NmHandleManager<T> {
    _objs: NmHandleObjects,
    handler: CallbackQueueReceiver<TxRequest, TxCompletion>,
    sender: QueueSender<RxRequest, RxCompletion>,
    tx_bc: BufferController,
    rx_bc: BufferController,
    flags: AtomicU64,
    client_name: String,
    client_id: u64,
    data: T,
}

impl NmHandle {
    pub async fn handle<'a, F, Fut>(self: &'a Arc<NmHandle>, f: F) -> Result<(), QueueError>
    where
        F: Fn(&'a Arc<NmHandle>, u32, RxRequest) -> Fut,
        Fut: Future<Output = RxCompletion>,
    {
        self.handler.handle(move |id, req| f(self, id, req)).await
    }

    pub async fn submit(&self, req: TxRequest) -> Result<TxCompletion, QueueError> {
        self.sender.submit_and_wait(req).await
    }

    pub fn submit_no_wait(&self, req: TxRequest) {
        self.sender.submit_no_wait(req, SubmissionFlags::NON_BLOCK);
    }

    /*
    pub fn tx_buffer_controller(&self) -> &BufferController {
        &self.tx_bc
    }

    pub fn rx_buffer_controller(&self) -> &BufferController {
        &self.rx_bc
    }
    */

    pub fn allocatable_buffer_controller(&self) -> &BufferController {
        &self.tx_bc
    }

    pub fn set_dead(&self) {
        self.flags.fetch_or(DEAD, Ordering::SeqCst);
    }

    pub fn is_dead(&self) -> bool {
        self.flags.load(Ordering::SeqCst) & DEAD != 0
    }

    pub fn set_closed(&self) {
        self.flags.fetch_or(CLOSED, Ordering::SeqCst);
    }

    pub fn is_closed(&self) -> bool {
        self.flags.load(Ordering::SeqCst) & CLOSED != 0
    }

    pub fn is_terminated(&self) -> bool {
        self.is_closed() || self.is_dead()
    }

    pub fn get_incoming_buffer(&self, pd: PacketData) -> ManagedBuffer {
        ManagedBuffer::new_unowned(&self.rx_bc, pd.buffer_idx, pd.buffer_len as usize)
    }

    pub fn id(&self) -> u64 {
        self.client_id
    }

    pub fn client_name(&self) -> &str {
        &self.client_name
    }
}

#[cfg(feature = "manager")]
impl<T> NmHandleManager<T> {
    pub fn data(&self) -> &T {
        &self.data
    }

    pub async fn receive(&self) -> Result<(u32, TxRequest), QueueError> {
        if self.is_terminated() {
            Err(QueueError::Unknown)
        } else {
            self.handler.receive().await
        }
    }

    pub async fn complete(&self, id: u32, reply: TxCompletion) -> Result<(), QueueError> {
        self.handler.complete(id, reply).await
    }

    pub async fn submit(&self, req: RxRequest) -> Result<RxCompletion, QueueError> {
        if self.is_terminated() {
            return Err(QueueError::Unknown);
        }
        self.sender.submit_and_wait(req).await
    }

    pub fn submit_no_wait(&self, req: RxRequest) {
        self.sender.submit_no_wait(req, SubmissionFlags::NON_BLOCK);
    }

    /*
    pub fn tx_buffer_controller(&self) -> &BufferController {
        &self.tx_bc
    }

    pub fn rx_buffer_controller(&self) -> &BufferController {
        &self.rx_bc
    }
    */

    pub fn allocatable_buffer_controller(&self) -> &BufferController {
        &self.rx_bc
    }

    pub fn set_dead(&self) {
        self.flags.fetch_or(DEAD, Ordering::SeqCst);
    }

    pub fn is_dead(&self) -> bool {
        self.flags.load(Ordering::SeqCst) & DEAD != 0
    }

    pub fn set_closed(&self) {
        self.flags.fetch_or(CLOSED, Ordering::SeqCst);
    }

    pub fn is_closed(&self) -> bool {
        self.flags.load(Ordering::SeqCst) & CLOSED != 0
    }

    pub fn is_terminated(&self) -> bool {
        self.is_closed() || self.is_dead()
    }

    pub fn get_incoming_buffer(&self, pd: PacketData) -> ManagedBuffer {
        ManagedBuffer::new_unowned(&self.tx_bc, pd.buffer_idx, pd.buffer_len as usize)
    }

    pub fn id(&self) -> u64 {
        self.client_id
    }

    pub fn client_name(&self) -> &str {
        &self.client_name
    }
}

impl Drop for NmHandle {
    fn drop(&mut self) {
        println!("dropping nm handle");
        if !self.is_dead() {
            self.submit_no_wait(TxRequest::Close);
        }
    }
}

#[cfg(feature = "manager")]
impl<T> Drop for NmHandleManager<T> {
    fn drop(&mut self) {
        println!("dropping nm handle manager");
        if !self.is_dead() {
            self.submit_no_wait(RxRequest::Close);
        }
    }
}

impl core::fmt::Debug for NmHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NmHandle")
            .field("client_id", &self.client_id)
            .field("client_name", &self.client_name)
            .field("flags", &self.flags)
            .finish()
    }
}

#[cfg(feature = "manager")]
impl<T> core::fmt::Debug for NmHandleManager<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("NmHandleManager")
            .field("client_id", &self.client_id)
            .field("client_name", &self.client_name)
            .field("flags", &self.flags)
            .finish()
    }
}

pub fn open_nm_handle(client_name: &str) -> Option<NmHandle> {
    let id = std::env::var("NETOBJ").ok()?;
    let id = id
        .parse::<u128>()
        .unwrap_or_else(|_| panic!("failed to parse object ID string {}", id));
    let id = ObjID::new(id);
    let objs = client_rendezvous(id, client_name);
    let client_id = objs.client_id;
    let objs = NmHandleObjects {
        tx_queue: Object::init_id(
            objs.tx_queue,
            Protections::READ | Protections::WRITE,
            ObjectInitFlags::empty(),
        )
        .ok()?,
        rx_queue: Object::init_id(
            objs.rx_queue,
            Protections::READ | Protections::WRITE,
            ObjectInitFlags::empty(),
        )
        .ok()?,
        tx_buf: Object::init_id(
            objs.tx_buf,
            Protections::READ | Protections::WRITE,
            ObjectInitFlags::empty(),
        )
        .ok()?,
        rx_buf: Object::init_id(objs.rx_buf, Protections::READ, ObjectInitFlags::empty()).ok()?,
    };
    let sender = QueueSender::new(objs.tx_queue.clone().into());
    let handler = CallbackQueueReceiver::new(objs.rx_queue.clone().into());
    let tx_bc = BufferController::new(false, true, objs.tx_buf.clone());
    let rx_bc = BufferController::new(false, false, objs.rx_buf.clone());
    let handle = NmHandle {
        _objs: objs,
        handler,
        sender,
        tx_bc,
        rx_bc,
        flags: AtomicU64::new(0),
        client_name: client_name.to_owned(),
        client_id,
    };
    Some(handle)
}

#[cfg(feature = "manager")]
pub fn server_open_nm_handle<T>(data: T) -> Option<NmHandleManager<T>> {
    use std::ffi::CStr;

    let id = std::env::var("NETOBJ").ok()?;
    let id = id
        .parse::<u128>()
        .unwrap_or_else(|_| panic!("failed to parse object ID string {}", id));
    let id = ObjID::new(id);
    let objs = server_rendezvous(id);
    let client_name = CStr::from_bytes_with_nul(
        &objs.client_name[0..=objs.client_name.iter().position(|x| *x == 0).unwrap_or(0)],
    )
    .unwrap_or_else(|_| CStr::from_bytes_with_nul(&[0]).unwrap());
    let client_name = client_name.to_str().unwrap_or("").to_owned();
    let client_id = objs.client_id;
    let objs = NmHandleObjects {
        tx_queue: Object::init_id(
            objs.tx_queue,
            Protections::READ | Protections::WRITE,
            ObjectInitFlags::empty(),
        )
        .ok()?,
        rx_queue: Object::init_id(
            objs.rx_queue,
            Protections::READ | Protections::WRITE,
            ObjectInitFlags::empty(),
        )
        .ok()?,
        tx_buf: Object::init_id(objs.tx_buf, Protections::READ, ObjectInitFlags::empty()).ok()?,
        rx_buf: Object::init_id(
            objs.rx_buf,
            Protections::READ | Protections::WRITE,
            ObjectInitFlags::empty(),
        )
        .ok()?,
    };
    let sender = QueueSender::new(objs.rx_queue.clone().into());
    let handler = CallbackQueueReceiver::new(objs.tx_queue.clone().into());
    let tx_bc = BufferController::new(true, true, objs.tx_buf.clone());
    let rx_bc = BufferController::new(true, false, objs.rx_buf.clone());
    let handle = NmHandleManager {
        _objs: objs,
        handler,
        sender,
        tx_bc,
        rx_bc,
        flags: AtomicU64::new(0),
        client_name,
        client_id,
        data,
    };
    Some(handle)
}