830c073627410e9c6541a4b174147f50e51d72c3
[archipelago] / xseg / peers / user / mpeer.c
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <sys/types.h>
5 #include <unistd.h>
6 #include <xseg/xseg.h>
7 #include <pthread.h>
8 #include <mpeer.h>
9 #include <sys/syscall.h>
10 #include <sys/time.h>
11 #include <signal.h>
12
13 #define REARRANGE(__fun_name__, __format__, ...) __format__ "%s", __fun_name__, ##__VA_ARGS__
14 #define LOG(level, ...)                                              \
15                 do {                                                               \
16                         if (level <=  verbose) {                           \
17                                 fprintf(stderr, "%s: "  REARRANGE( __func__ , ## __VA_ARGS__, "" )); \
18                         }                                                          \
19                 }while (0)
20
21
22 unsigned int verbose = 0;
23 struct log_ctx lc;
24
25 struct thread {
26         struct peerd *peer;
27         pthread_t tid;
28         pthread_cond_t cond;
29         pthread_mutex_t lock;
30         void (*func)(void *arg);
31         void *arg;
32 };
33
34
35 inline int canDefer(struct peerd *peer)
36 {
37         return !(peer->defer_portno == NoPort);
38 }
39
40 void print_req(struct xseg *xseg, struct xseg_request *req)
41 {
42         char target[64], data[64];
43         char *req_target, *req_data;
44         unsigned int end = (req->targetlen> 63) ? 63 : req->targetlen;
45         req_target = xseg_get_target(xseg, req);
46         req_data = xseg_get_data(xseg, req);
47
48         if (1) {
49                 strncpy(target, req_target, end);
50                 target[end] = 0;
51                 strncpy(data, req_data, 63);
52                 data[63] = 0;
53                 printf("req id:%lu, op:%u %llu:%lu serviced: %lu, reqstate: %u\n"
54                                 "src: %u, st: %u, dst: %u dt: %u\n"
55                                 "target[%u]:'%s', data[%llu]:\n%s------------------\n\n",
56                                 (unsigned long)(req),
57                                 (unsigned int)req->op,
58                                 (unsigned long long)req->offset,
59                                 (unsigned long)req->size,
60                                 (unsigned long)req->serviced,
61                                 (unsigned int)req->state,
62                                 (unsigned int)req->src_portno,
63                                 (unsigned int)req->src_transit_portno,
64                                 (unsigned int)req->dst_portno,
65                                 (unsigned int)req->dst_transit_portno,
66                                 (unsigned int)req->targetlen, target,
67                                 (unsigned long long)req->datalen, data);
68         }
69 }
70 void log_pr(char *msg, struct peer_req *pr)
71 {
72         char target[64], data[64];
73         char *req_target, *req_data;
74         struct peerd *peer = pr->peer;
75         struct xseg *xseg = pr->peer->xseg;
76         req_target = xseg_get_target(xseg, pr->req);
77         req_data = xseg_get_data(xseg, pr->req);
78         /* null terminate name in case of req->target is less than 63 characters,
79          * and next character after name (aka first byte of next buffer) is not
80          * null
81          */
82         unsigned int end = (pr->req->targetlen> 63) ? 63 : pr->req->targetlen;
83         if (verbose) {
84                 strncpy(target, req_target, end);
85                 target[end] = 0;
86                 strncpy(data, req_data, 63);
87                 data[63] = 0;
88                 printf("%s: req id:%u, op:%u %llu:%lu serviced: %lu, retval: %lu, reqstate: %u\n"
89                                 "target[%u]:'%s', data[%llu]:\n%s------------------\n\n",
90                                 msg,
91                                 (unsigned int)(pr - peer->peer_reqs),
92                                 (unsigned int)pr->req->op,
93                                 (unsigned long long)pr->req->offset,
94                                 (unsigned long)pr->req->size,
95                                 (unsigned long)pr->req->serviced,
96                                 (unsigned long)pr->retval,
97                                 (unsigned int)pr->req->state,
98                                 (unsigned int)pr->req->targetlen, target,
99                                 (unsigned long long)pr->req->datalen, data);
100         }
101 }
102
103 inline struct peer_req *alloc_peer_req(struct peerd *peer)
104 {
105         xqindex idx = xq_pop_head(&peer->free_reqs, 1);
106         if (idx == Noneidx)
107                 return NULL;
108         return peer->peer_reqs + idx;
109 }
110
111 inline void free_peer_req(struct peerd *peer, struct peer_req *pr)
112 {
113         xqindex idx = pr - peer->peer_reqs;
114         pr->req = NULL;
115         xq_append_head(&peer->free_reqs, idx, 1);
116 }
117
118 inline static struct thread* alloc_thread(struct peerd *peer)
119 {
120         xqindex idx = xq_pop_head(&peer->threads, 1);
121         if (idx == Noneidx)
122                 return NULL;
123         return peer->thread + idx;
124 }
125
126 inline static void free_thread(struct peerd *peer, struct thread *t)
127 {
128         xqindex idx = t - peer->thread;
129         xq_append_head(&peer->threads, idx, 1);
130 }
131
132
133 inline static void __wake_up_thread(struct thread *t)
134 {
135         pthread_mutex_lock(&t->lock);
136         pthread_cond_signal(&t->cond);
137         pthread_mutex_unlock(&t->lock);
138 }
139
140 inline static void wake_up_thread(struct thread* t)
141 {
142         if (t){
143                 __wake_up_thread(t);
144         }
145 }
146
147 inline static int wake_up_next_thread(struct peerd *peer)
148 {
149         //struct thread *t = alloc_thread(peer);
150         //wake_up_thread(t);
151         //return t;
152         return (xseg_signal(peer->xseg, peer->portno));
153 }
154
155 struct timeval resp_start, resp_end, resp_accum = {0, 0};
156 uint64_t responds = 0;
157 void get_responds_stats(){
158                 printf("Time waiting respond %lu.%06lu sec for %llu times.\n",
159                                 //(unsigned int)(t - peer->thread),
160                                 resp_accum.tv_sec, resp_accum.tv_usec, (long long unsigned int) responds);
161 }
162
163 //FIXME error check
164 void fail(struct peerd *peer, struct peer_req *pr)
165 {
166         struct xseg_request *req = pr->req;
167         uint32_t p;
168         XSEGLOG2(&lc, D, "failing req %u", (unsigned int) (pr - peer->peer_reqs));
169         req->state |= XS_FAILED;
170         //xseg_set_req_data(peer->xseg, pr->req, NULL);
171         p = xseg_respond(peer->xseg, req, peer->portno, X_ALLOC);
172         xseg_signal(peer->xseg, p);
173         free_peer_req(peer, pr);
174         wake_up_next_thread(peer);
175 }
176
177 //FIXME error check
178 void complete(struct peerd *peer, struct peer_req *pr)
179 {
180         struct xseg_request *req = pr->req;
181         uint32_t p;
182         req->state |= XS_SERVED;
183         //xseg_set_req_data(peer->xseg, pr->req, NULL);
184         //gettimeofday(&resp_start, NULL);
185         p = xseg_respond(peer->xseg, req, peer->portno, X_ALLOC);
186         //gettimeofday(&resp_end, NULL);
187         //responds++;
188         //timersub(&resp_end, &resp_start, &resp_end);
189         //timeradd(&resp_end, &resp_accum, &resp_accum);
190         //printf("xseg_signal: %u\n", p);
191         xseg_signal(peer->xseg, p);
192         free_peer_req(peer, pr);
193         wake_up_next_thread(peer);
194 }
195
196 void pending(struct peerd *peer, struct peer_req *pr)
197 {
198                 pr->req->state = XS_PENDING;
199 }
200
201 static void handle_accepted(struct peerd *peer, struct peer_req *pr, 
202                                 struct xseg_request *req)
203 {
204         struct xseg_request *xreq = pr->req;
205         //assert xreq == req;
206         XSEGLOG2(&lc, D, "Handle accepted");
207         xreq->serviced = 0;
208         //xreq->state = XS_ACCEPTED;
209         pr->retval = 0;
210         dispatch(peer, pr, req);
211 }
212
213 static void handle_received(struct peerd *peer, struct peer_req *pr,
214                                 struct xseg_request *req)
215 {
216         //struct xseg_request *req = pr->req;
217         //assert req->state != XS_ACCEPTED;
218         XSEGLOG2(&lc, D, "Handle received \n");
219         dispatch(peer, pr, req);
220
221 }
222 struct timeval sub_start, sub_end, sub_accum = {0, 0};
223 uint64_t submits = 0;
224 void get_submits_stats(){
225                 printf("Time waiting submit %lu.%06lu sec for %llu times.\n",
226                                 //(unsigned int)(t - peer->thread),
227                                 sub_accum.tv_sec, sub_accum.tv_usec, (long long unsigned int) submits);
228 }
229
230 int submit_peer_req(struct peerd *peer, struct peer_req *pr)
231 {
232         uint32_t ret;
233         struct xseg_request *req = pr->req;
234         // assert req->portno == peer->portno ?
235         //TODO small function with error checking
236         XSEGLOG2 (&lc, D, "submitting peer req %u\n", (unsigned int)(pr - peer->peer_reqs));
237         ret = xseg_set_req_data(peer->xseg, req, (void *)(pr));
238         if (ret < 0)
239                 return -1;
240         //printf("pr: %x , req_data: %x \n", pr, xseg_get_req_data(peer->xseg, req));
241         //gettimeofday(&sub_start, NULL);
242         ret = xseg_submit(peer->xseg, req, peer->portno, X_ALLOC);
243         //gettimeofday(&sub_end, NULL);
244         //submits++;
245         //timersub(&sub_end, &sub_start, &sub_end);
246         //timeradd(&sub_end, &sub_accum, &sub_accum);
247         if (ret == NoPort)
248                 return -1;
249         xseg_signal(peer->xseg, ret);
250         return 0;
251 }
252
253 int thread_execute(struct peerd *peer, void (*func)(void *arg), void *arg)
254 {
255         struct thread *t = alloc_thread(peer);
256         if (t) {
257                 t->func = func;
258                 t->arg = arg;
259                 wake_up_thread(t);
260                 return 0;
261         } else
262                 // we could hijack a thread
263                 return -1;
264 }
265
266 static void* thread_loop(void *arg)
267 {
268         struct thread *t = (struct thread *) arg;
269         struct peerd *peer = t->peer;
270         struct xseg *xseg = peer->xseg;
271         uint32_t portno = peer->portno;
272         struct peer_req *pr;
273         uint64_t threshold=1000;
274         pid_t pid =syscall(SYS_gettid);
275         uint64_t loops;
276         struct xseg_request *accepted, *received;
277         int r;
278                 
279         XSEGLOG2(&lc, D, "thread %u\n",  (unsigned int) (t- peer->thread));
280
281         XSEGLOG2(&lc, I, "Thread %u has tid %u.\n", (unsigned int) (t- peer->thread), pid);
282         xseg_init_local_signal(xseg, portno);
283         for (;;) {
284                 if (t->func) {
285                         XSEGLOG2(&lc, D, "Thread %u executes function\n", (unsigned int) (t- peer->thread));
286                         xseg_cancel_wait(xseg, portno);
287                         t->func(t->arg);
288                         t->func = NULL;
289                         t->arg = NULL;
290                         continue;
291                 }
292
293                 for(loops= threshold; loops > 0; loops--) {
294                         accepted = NULL;
295                         received = NULL;
296                         if (loops == 1)
297                                 xseg_prepare_wait(xseg, portno);
298
299 //                      if (xq_count(&peer->xport->request_queue)){
300                                 pr = alloc_peer_req(peer);
301                                 if (pr) {
302                                         accepted = xseg_accept(xseg, peer->portno);
303                                         if (accepted) {
304                                                 XSEGLOG2(&lc, D, "Thread %u accepted\n", (unsigned int) (t- peer->thread));
305                                                 pr->req = accepted;
306                                                 xseg_cancel_wait(xseg, portno);
307                                                 wake_up_next_thread(peer);
308                                                 handle_accepted(peer, pr, accepted);
309                                                 loops = threshold;
310                                         }
311                                         else {
312                                                 free_peer_req(peer, pr);
313                                         }
314                                 }
315 //                      }
316 //                      if (xq_count(&peer->xport->reply_queue)){
317                                 received = xseg_receive(xseg, peer->portno);
318                                 if (received) {
319                                         //printf("received req id: %u\n", received - xseg->requests);
320                                         //print_req(peer->xseg, received);
321                                         r =  xseg_get_req_data(xseg, received, (void **) &pr);
322                                         if (r < 0 || !pr){
323                                                 //FIXME what to do here ?
324                                                 XSEGLOG2(&lc, W, "Received request with no pr data\n");
325                                                 xseg_respond(peer->xseg, received, peer->portno, X_ALLOC);
326                                                 //if fails, put req
327                                         }
328                                         //fail(peer, received);
329                                         //assert pr->req == received;
330                                         xseg_cancel_wait(xseg, portno);
331                                         wake_up_next_thread(peer);
332                                         handle_received(peer, pr, received);
333                                         loops = threshold;
334                                 }
335 //                      }
336                 }
337                 XSEGLOG2(&lc, I, "Thread %u goes to sleep\n", (unsigned int) (t- peer->thread));
338                 xseg_wait_signal(xseg, 10000000UL);
339                 xseg_cancel_wait(xseg, portno);
340                 XSEGLOG2(&lc, I, "Thread %u woke up\n", (unsigned int) (t- peer->thread));
341         }
342         return NULL;
343 }
344
345 void defer_request(struct peerd *peer, struct peer_req *pr)
346 {
347         // assert canDefer(peer);
348 //      xseg_submit(peer->xseg, peer->defer_portno, pr->req);
349 //      xseg_signal(peer->xseg, peer->defer_portno);
350 //      free_peer_req(peer, pr);
351 }
352
353 static int peerd_loop(struct peerd *peer) 
354 {
355         if (peer->interactive_func)
356                 peer->interactive_func();
357         for (;;) {
358                 pthread_join(peer->thread[0].tid, NULL);
359         }
360         return 0;
361 }
362
363 static struct xseg *join(char *spec)
364 {
365         struct xseg_config config;
366         struct xseg *xseg;
367
368         (void)xseg_parse_spec(spec, &config);
369         xseg = xseg_join(config.type, config.name, "pthread", NULL);
370         if (xseg)
371                 return xseg;
372
373         (void)xseg_create(&config);
374         return xseg_join(config.type, config.name, "pthread", NULL);
375 }
376
377 int peerd_start_threads(struct peerd *peer)
378 {
379         int i;
380         uint32_t nr_threads = peer->nr_threads;
381         //TODO err check
382         for (i = 0; i < nr_threads; i++) {
383                 peer->thread[i].peer = peer;
384                 pthread_cond_init(&peer->thread[i].cond,NULL);
385                 pthread_mutex_init(&peer->thread[i].lock, NULL);
386                 pthread_create(&peer->thread[i].tid, NULL, thread_loop, (void *)(peer->thread + i));
387                 peer->thread[i].func = NULL;
388                 peer->thread[i].arg = NULL;
389
390         }
391         return 0;
392 }
393
394 static struct peerd* peerd_init(uint32_t nr_ops, char* spec, long portno, uint32_t nr_threads, uint32_t defer_portno)
395 {
396         int i;
397         struct peerd *peer;
398         peer = malloc(sizeof(struct peerd));
399         if (!peer) {
400                 perror("malloc");
401                 return NULL;
402         }
403         peer->nr_ops = nr_ops;
404         peer->defer_portno = defer_portno;
405         peer->nr_threads = nr_threads;
406
407         peer->thread = calloc(nr_threads, sizeof(struct thread));
408         if (!peer->thread)
409                 goto malloc_fail;
410         peer->peer_reqs = calloc(nr_ops, sizeof(struct peer_req));
411         if (!peer->peer_reqs){
412 malloc_fail:
413                 perror("malloc");
414                 return NULL;
415         }
416
417         if (!xq_alloc_seq(&peer->free_reqs, nr_ops, nr_ops))
418                 goto malloc_fail;
419         if (!xq_alloc_empty(&peer->threads, nr_threads))
420                 goto malloc_fail;
421
422         if (xseg_initialize()){
423                 printf("cannot initialize library\n");
424                 return NULL;
425         }
426         peer->xseg = join(spec);
427         if (!peer->xseg) 
428                 return NULL;
429
430         peer->xport = xseg_bind_port(peer->xseg, portno, NULL);
431         if (!peer->xport){
432                 printf("cannot bind to port %ld\n", portno);
433                 return NULL;
434         }
435         printf("%lx\n", (unsigned long) peer->xport);
436         peer->portno = xseg_portno(peer->xseg, peer->xport);
437         printf("Peer on port %u/%u\n", peer->portno,
438                         peer->xseg->config.nr_ports);
439
440         for (i = 0; i < nr_ops; i++) {
441                 peer->peer_reqs[i].peer = peer;
442                 peer->peer_reqs[i].req = NULL;
443                 peer->peer_reqs[i].retval = 0;
444                 peer->peer_reqs[i].priv = NULL;
445         }
446         peer->interactive_func = NULL;
447         return peer;
448 }
449
450
451 int main(int argc, char *argv[])
452 {
453         struct peerd *peer = NULL;
454         //parse args
455         char *spec = "";
456         int i, r;
457         long portno = -1;
458         //set defaults here
459         uint32_t nr_ops = 16;
460         uint32_t nr_threads = 16 ;
461         unsigned int debug_level = 0;
462         uint32_t defer_portno = NoPort;
463         char *logfile = NULL;
464
465         //capture here -g spec, -n nr_ops, -p portno, -t nr_threads -v verbose level
466         // -dp xseg_portno to defer blocking requests
467         // -l log file ?
468         //TODO print messages on arg parsing error
469         
470         for (i = 1; i < argc; i++) {
471                 if (!strcmp(argv[i], "-g") && i + 1 < argc) {
472                         spec = argv[i+1];
473                         i += 1;
474                         continue;
475                 }
476
477                 if (!strcmp(argv[i], "-p") && i + 1 < argc) {
478                         portno = strtoul(argv[i+1], NULL, 10);
479                         i += 1;
480                         continue;
481                 }
482
483                 if (!strcmp(argv[i], "-n") && i + 1 < argc) {
484                         nr_ops = strtoul(argv[i+1], NULL, 10);
485                         i += 1;
486                         continue;
487                 }
488                 if (!strcmp(argv[i], "-v") && i + 1 < argc ) {
489                         debug_level = atoi(argv[i+1]);
490                         i += 1;
491                         continue;
492                 }
493                 if (!strcmp(argv[i], "-t") && i + 1 < argc ) {
494                         nr_threads = strtoul(argv[i+1], NULL, 10);
495                         i += 1;
496                         continue;
497                 }
498                 if (!strcmp(argv[i], "-dp") && i + 1 < argc ) {
499                         defer_portno = strtoul(argv[i+1], NULL, 10);
500                         i += 1;
501                         continue;
502                 }
503                 if (!strcmp(argv[i], "-l") && i + 1 < argc ) {
504                         logfile = argv[i+1];
505                         i += 1;
506                         continue;
507                 }
508
509         }
510         init_logctx(&lc, argv[0], debug_level, logfile);
511         XSEGLOG2(&lc, D, "Main thread has tid %ld.\n", syscall(SYS_gettid));
512         
513         //TODO perform argument sanity checks
514         verbose = debug_level;
515
516         //TODO err check
517         peer = peerd_init(nr_ops, spec, portno, nr_threads, defer_portno);
518         if (!peer)
519                 return -1;
520         r = custom_peer_init(peer, argc, argv);
521         if (r < 0)
522                 return -1;
523         peerd_start_threads(peer);
524         return peerd_loop(peer);
525 }