streamers / chunklock.c @ b8a88cc5
History | View | Annotate | Download (1.82 KB)
1 |
/*
|
---|---|
2 |
* Copyright (c) 2010 Luca Abeni
|
3 |
* Copyright (c) 2010 Csaba Kiraly
|
4 |
*
|
5 |
* This is free software; see gpl-3.0.txt
|
6 |
*/
|
7 |
#include <stdlib.h> |
8 |
#include <stdio.h> |
9 |
#include <string.h> |
10 |
#include <stdint.h> |
11 |
|
12 |
#include "chunklock.h" |
13 |
|
14 |
#include "net_helper.h" |
15 |
|
16 |
static struct timeval toutdiff = {0, 300000}; |
17 |
|
18 |
|
19 |
|
20 |
struct lock {
|
21 |
int chunkid;
|
22 |
struct nodeID *peer;
|
23 |
struct timeval timestamp;
|
24 |
}; |
25 |
|
26 |
struct lock *locks;
|
27 |
static size_t lsize, lcount=0; |
28 |
#define LSIZE_INCREMENT 10 |
29 |
|
30 |
void locks_init()
|
31 |
{ |
32 |
if (!locks) {
|
33 |
lsize = LSIZE_INCREMENT; |
34 |
locks = malloc(sizeof(struct lock) * lsize); |
35 |
lcount = 0;
|
36 |
} |
37 |
|
38 |
if (lcount == lsize) {
|
39 |
lsize += LSIZE_INCREMENT; |
40 |
locks = realloc(locks , sizeof(struct lock) * lsize); |
41 |
} |
42 |
|
43 |
if (!locks) {
|
44 |
fprintf(stderr, "Error allocating memory for locks!\n");
|
45 |
exit(EXIT_FAILURE); |
46 |
} |
47 |
} |
48 |
|
49 |
int chunk_lock_timed_out(struct lock *l) |
50 |
{ |
51 |
struct timeval tnow,tout;
|
52 |
gettimeofday(&tnow, NULL);
|
53 |
timeradd(&l->timestamp, &toutdiff, &tout); |
54 |
|
55 |
return timercmp(&tnow, &tout, >);
|
56 |
} |
57 |
|
58 |
void chunk_lock_remove(struct lock *l){ |
59 |
nodeID_free(l->peer); |
60 |
memmove(l, l+1, sizeof(struct lock) * (locks+lcount-l-1)); |
61 |
lcount--; |
62 |
} |
63 |
|
64 |
void chunk_locks_cleanup(){
|
65 |
int i;
|
66 |
|
67 |
for (i=lcount-1; i>=0; i--) { |
68 |
if (chunk_lock_timed_out(locks+i)) {
|
69 |
chunk_lock_remove(locks+i); |
70 |
} |
71 |
} |
72 |
} |
73 |
|
74 |
void chunk_lock(int chunkid,struct peer *from){ |
75 |
locks_init(); |
76 |
locks[lcount].chunkid = chunkid; |
77 |
locks[lcount].peer = nodeid_dup(from->id); |
78 |
gettimeofday(&locks[lcount].timestamp,NULL);
|
79 |
lcount++; |
80 |
} |
81 |
|
82 |
void chunk_unlock(int chunkid){ |
83 |
int i;
|
84 |
|
85 |
for (i=0; i<lcount; i++) { |
86 |
if (locks[i].chunkid == chunkid) {
|
87 |
chunk_lock_remove(locks+i); |
88 |
break;
|
89 |
} |
90 |
} |
91 |
} |
92 |
|
93 |
int chunk_islocked(int chunkid){ |
94 |
int i;
|
95 |
|
96 |
chunk_locks_cleanup(); |
97 |
|
98 |
for (i=0; i<lcount; i++) { |
99 |
if (locks[i].chunkid == chunkid) {
|
100 |
return 1; |
101 |
} |
102 |
} |
103 |
return 0; |
104 |
} |