Statistics
| Branch: | Revision:

streamers / chunklock.c @ 63ebb93d

History | View | Annotate | Download (1.86 KB)

1
/*
2
 *  Copyright (c) 2010 Csaba Kiraly
3
 *  Copyright (c) 2010 Luca Abeni
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 "compatibility/timer.h"
13

    
14
#include "chunklock.h"
15

    
16
#include "net_helper.h"
17

    
18
static struct timeval toutdiff = {1, 0};
19

    
20

    
21

    
22
struct lock {
23
  int chunkid;
24
  struct nodeID *peer;
25
  struct timeval timestamp;
26
};
27

    
28
struct lock *locks;
29
static size_t lsize, lcount=0;
30
#define LSIZE_INCREMENT 10
31

    
32
void locks_init()
33
{
34
  if (!locks) {
35
    lsize = LSIZE_INCREMENT;
36
    locks = malloc(sizeof(struct lock) * lsize);
37
    lcount = 0;
38
  }
39

    
40
  if (lcount == lsize) {
41
    lsize += LSIZE_INCREMENT;
42
    locks = realloc(locks , sizeof(struct lock) * lsize);
43
  }
44

    
45
  if (!locks) {
46
    fprintf(stderr, "Error allocating memory for locks!\n");
47
    exit(EXIT_FAILURE);
48
  }
49
}
50

    
51
int chunk_lock_timed_out(struct lock *l)
52
{
53
  struct timeval tnow,tout;
54
  gettimeofday(&tnow, NULL);
55
  timeradd(&l->timestamp, &toutdiff, &tout);
56

    
57
  return timercmp(&tnow, &tout, >);
58
}
59

    
60
void chunk_lock_remove(struct lock *l){
61
  nodeid_free(l->peer);
62
  memmove(l, l+1, sizeof(struct lock) * (locks+lcount-l-1));
63
  lcount--;
64
}
65

    
66
void chunk_locks_cleanup(){
67
  int i;
68

    
69
  for (i=lcount-1; i>=0; i--) {
70
    if (chunk_lock_timed_out(locks+i)) {
71
      chunk_lock_remove(locks+i);
72
    }
73
  }
74
}
75

    
76
void chunk_lock(int chunkid,struct peer *from){
77
  locks_init();
78
  locks[lcount].chunkid = chunkid;
79
  locks[lcount].peer = from ? nodeid_dup(from->id) : NULL;
80
  gettimeofday(&locks[lcount].timestamp,NULL);
81
  lcount++;
82
}
83

    
84
void chunk_unlock(int chunkid){
85
  int i;
86

    
87
  for (i=0; i<lcount; i++) {
88
    if (locks[i].chunkid == chunkid) {
89
      chunk_lock_remove(locks+i);
90
      break;
91
    }
92
  }
93
}
94

    
95
int chunk_islocked(int chunkid){
96
  int i;
97

    
98
  chunk_locks_cleanup();
99

    
100
  for (i=0; i<lcount; i++) {
101
    if (locks[i].chunkid == chunkid) {
102
      return 1;
103
    }
104
  }
105
  return 0;
106
}