More clean-ups and cool template stuff
[invirt/third/libt4.git] / lock_client.h
1 // lock client interface.
2
3 #ifndef lock_client_h
4
5 #define lock_client_h
6
7 #ifdef __cplusplus
8
9 #include <string>
10 #include "lock_protocol.h"
11 #include "rpc/rpc.h"
12 #include "lang/verify.h"
13 #include "rpc/fifo.h"
14 #include "rsm_client.h"
15 #include "lock.h"
16
17 class lock_release_user {
18     public:
19         virtual void dorelease(lock_protocol::lockid_t) = 0;
20         virtual ~lock_release_user() {}
21 };
22
23 using std::string;
24 using std::map;
25 using std::thread;
26 using std::list;
27
28 class lock_state {
29 public:
30     enum {
31         none = 0,
32         retrying,
33         free,
34         locked,
35         acquiring,
36         releasing
37     } state = none;
38     thread::id held_by;
39     list<thread::id> wanted_by;
40     mutex m;
41     map<thread::id, cond> c;
42     lock_protocol::xid_t xid;
43     void wait(lock & mutex_lock);
44     void signal();
45     void signal(thread::id who);
46 };
47
48 typedef map<lock_protocol::lockid_t, lock_state> lock_map;
49
50 // Clients that caches locks.  The server can revoke locks using
51 // lock_revoke_server.
52 class lock_client {
53     private:
54         rpcc *cl;
55         thread releaser_thread;
56         rsm_client *rsmc;
57         class lock_release_user *lu;
58         unsigned int rlock_port;
59         string hostname;
60         string id;
61         mutex xid_mutex;
62         lock_protocol::xid_t next_xid;
63         fifo<lock_protocol::lockid_t> release_fifo;
64         mutex lock_table_lock;
65         lock_map lock_table;
66         lock_state &get_lock_state(lock_protocol::lockid_t lid);
67     public:
68         static unsigned int last_port;
69         lock_client(string xdst, class lock_release_user *l = 0);
70         ~lock_client() {}
71         lock_protocol::status acquire(lock_protocol::lockid_t);
72         lock_protocol::status release(lock_protocol::lockid_t);
73         int stat(lock_protocol::lockid_t);
74         void releaser();
75         rlock_protocol::status revoke_handler(int &, lock_protocol::lockid_t, lock_protocol::xid_t);
76         rlock_protocol::status retry_handler(int &, lock_protocol::lockid_t, lock_protocol::xid_t);
77 };
78
79 #endif // C++
80
81 extern "C" {
82
83 struct _t4_lock_client;
84 typedef struct _t4_lock_client t4_lock_client;
85
86 typedef enum {
87     T4_OK,
88     T4_RETRY,
89     T4_RPCERR,
90     T4_NOENT,
91     T4_IOERR
92 } t4_xxstatus;
93
94 typedef int t4_status;
95
96 typedef const char * t4_lockid_t;
97
98 t4_lock_client *t4_lock_client_new(const char *dst);
99 void t4_lock_client_delete(t4_lock_client *);
100 t4_status t4_lock_client_acquire(t4_lock_client *, t4_lockid_t);
101 t4_status t4_lock_client_release(t4_lock_client *, t4_lockid_t);
102 t4_status t4_lock_client_stat(t4_lock_client *, t4_lockid_t);
103
104 }
105
106 #endif