Debian Codegraph @

tools/ocaml/libs/xb/xb.ml

raw
1 (*
2 * Copyright (C) 2006-2007 XenSource Ltd.
3 * Copyright (C) 2008 Citrix Ltd.
4 * Author Vincent Hanquez <[email protected]>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU Lesser General Public License as published
8 * by the Free Software Foundation; version 2.1 only. with the special
9 * exception on linking described in file LICENSE.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *)
16
17 module Op = struct include Op end
18 module Packet = struct include Packet end
19
20 module BoundedQueue : sig
21 type ('a, 'b) t
22
23 (** [create ~capacity ~classify ~limit] creates a queue with maximum [capacity] elements.
24 This is burst capacity, each element is further classified according to [classify],
25 and each class can have its own [limit].
26 [capacity] is enforced as an overall limit.
27 The [limit] can be dynamic, and can be smaller than the number of elements already queued of that class,
28 in which case those elements are considered to use "burst capacity".
29 *)
30 val create: capacity:int -> classify:('a -> 'b) -> limit:('b -> int) -> ('a, 'b) t
31
32 (** [clear q] discards all elements from [q] *)
33 val clear: ('a, 'b) t -> unit
34
35 (** [can_push q] when [length q < capacity]. *)
36 val can_push: ('a, 'b) t -> 'b -> bool
37
38 (** [push e q] adds [e] at the end of queue [q] if [can_push q], or returns [None]. *)
39 val push: 'a -> ('a, 'b) t -> unit option
40
41 (** [pop q] removes and returns first element in [q], or raises [Queue.Empty]. *)
42 val pop: ('a, 'b) t -> 'a
43
44 (** [peek q] returns the first element in [q], or raises [Queue.Empty]. *)
45 val peek : ('a, 'b) t -> 'a
46
47 (** [length q] returns the current number of elements in [q] *)
48 val length: ('a, 'b) t -> int
49
50 (** [debug string_of_class q] prints queue usage statistics in an unspecified internal format. *)
51 val debug: ('b -> string) -> (_, 'b) t -> string
52 end = struct
53 type ('a, 'b) t =
54 { q: 'a Queue.t
55 ; capacity: int
56 ; classify: 'a -> 'b
57 ; limit: 'b -> int
58 ; class_count: ('b, int) Hashtbl.t
59 }
60
61 let create ~capacity ~classify ~limit =
62 { capacity; q = Queue.create (); classify; limit; class_count = Hashtbl.create 3 }
63
64 let get_count t classification = try Hashtbl.find t.class_count classification with Not_found -> 0
65
66 let can_push_internal t classification class_count =
67 Queue.length t.q < t.capacity && class_count < t.limit classification
68
69 let ok = Some ()
70
71 let push e t =
72 let classification = t.classify e in
73 let class_count = get_count t classification in
74 if can_push_internal t classification class_count then begin
75 Queue.push e t.q;
76 Hashtbl.replace t.class_count classification (class_count + 1);
77 ok
78 end
79 else
80 None
81
82 let can_push t classification =
83 can_push_internal t classification @@ get_count t classification
84
85 let clear t =
86 Queue.clear t.q;
87 Hashtbl.reset t.class_count
88
89 let pop t =
90 let e = Queue.pop t.q in
91 let classification = t.classify e in
92 let () = match get_count t classification - 1 with
93 | 0 -> Hashtbl.remove t.class_count classification (* reduces memusage *)
94 | n -> Hashtbl.replace t.class_count classification n
95 in
96 e
97
98 let peek t = Queue.peek t.q
99 let length t = Queue.length t.q
100
101 let debug string_of_class t =
102 let b = Buffer.create 128 in
103 Printf.bprintf b "BoundedQueue capacity: %d, used: {" t.capacity;
104 Hashtbl.iter (fun packet_class count ->
105 Printf.bprintf b " %s: %d" (string_of_class packet_class) count
106 ) t.class_count;
107 Printf.bprintf b "}";
108 Buffer.contents b
109 end
110
111
112 exception End_of_file
113 exception Eagain
114 exception Noent
115 exception Invalid
116 exception Reconnect
117
118 let _ =
119 Callback.register_exception "Xb.Reconnect" Reconnect
120
121 type backend_mmap =
122 {
123 mmap: Xenmmap.mmap_interface; (* mmaped interface = xs_ring *)
124 eventchn_notify: unit -> unit; (* function to notify through eventchn *)
125 mutable work_again: bool;
126 }
127
128 type backend_fd =
129 {
130 fd: Unix.file_descr;
131 }
132
133 type backend = Fd of backend_fd | Xenmmap of backend_mmap
134
135 type partial_buf = HaveHdr of Partial.pkt | NoHdr of int * bytes
136
137 (*
138 separate capacity reservation for replies and watch events:
139 this allows a domain to keep working even when under a constant flood of
140 watch events
141 *)
142 type capacity = { maxoutstanding: int; maxwatchevents: int }
143
144 module Queue = BoundedQueue
145
146 type packet_class =
147 | CommandReply
148 | Watchevent
149
150 let string_of_packet_class = function
151 | CommandReply -> "command_reply"
152 | Watchevent -> "watch_event"
153
154 type t =
155 {
156 backend: backend;
157 pkt_out: (Packet.t, packet_class) Queue.t;
158 mutable partial_in: partial_buf;
159 mutable partial_out: string;
160 capacity: capacity
161 }
162
163 let to_read con =
164 match con.partial_in with
165 | HaveHdr partial_pkt -> Partial.to_complete partial_pkt
166 | NoHdr (i, _) -> i
167
168 let debug t =
169 Printf.sprintf "XenBus state: partial_in: %d needed, partial_out: %d bytes, pkt_out: %d packets, %s"
170 (to_read t)
171 (String.length t.partial_out)
172 (Queue.length t.pkt_out)
173 (BoundedQueue.debug string_of_packet_class t.pkt_out)
174
175 let init_partial_in () = NoHdr
176 (Partial.header_size (), Bytes.make (Partial.header_size()) '\000')
177
178 let reconnect t = match t.backend with
179 | Fd _ ->
180 (* should never happen, so close the connection *)
181 raise End_of_file
182 | Xenmmap backend ->
183 Xs_ring.close backend.mmap;
184 backend.eventchn_notify ();
185 (* Clear our old connection state *)
186 Queue.clear t.pkt_out;
187 t.partial_in <- init_partial_in ();
188 t.partial_out <- ""
189
190 let queue con pkt = Queue.push pkt con.pkt_out
191
192 let read_fd back _con b len =
193 let rd = Unix.read back.fd b 0 len in
194 if rd = 0 then
195 raise End_of_file;
196 rd
197
198 let read_mmap back _con b len =
199 let s = Bytes.make len '\000' in
200 let rd = Xs_ring.read back.mmap s len in
201 Bytes.blit s 0 b 0 rd;
202 back.work_again <- (rd > 0);
203 if rd > 0 then
204 back.eventchn_notify ();
205 rd
206
207 let read con b len =
208 match con.backend with
209 | Fd backfd -> read_fd backfd con b len
210 | Xenmmap backmmap -> read_mmap backmmap con b len
211
212 let write_fd back _con b len =
213 Unix.write_substring back.fd b 0 len
214
215 let write_mmap back _con s len =
216 let ws = Xs_ring.write_substring back.mmap s len in
217 if ws > 0 then
218 back.eventchn_notify ();
219 ws
220
221 let write con s len =
222 match con.backend with
223 | Fd backfd -> write_fd backfd con s len
224 | Xenmmap backmmap -> write_mmap backmmap con s len
225
226 (* NB: can throw Reconnect *)
227 let output con =
228 (* get the output string from a string_of(packet) or partial_out *)
229 let s = if String.length con.partial_out > 0 then
230 con.partial_out
231 else if Queue.length con.pkt_out > 0 then
232 let pkt = Queue.pop con.pkt_out in
233 Packet.to_string pkt
234 else
235 "" in
236 (* send data from s, and save the unsent data to partial_out *)
237 if s <> "" then (
238 let len = String.length s in
239 let sz = write con s len in
240 let left = String.sub s sz (len - sz) in
241 con.partial_out <- left
242 );
243 (* after sending one packet, partial is empty *)
244 con.partial_out = ""
245
246 (* we can only process an input packet if we're guaranteed to have room
247 to store the response packet *)
248 let can_input con = Queue.can_push con.pkt_out CommandReply
249
250 (* NB: can throw Reconnect *)
251 let input con =
252 if not (can_input con) then None
253 else
254 let to_read = to_read con in
255
256 (* try to get more data from input stream *)
257 let b = Bytes.make to_read '\000' in
258 let sz = if to_read > 0 then read con b to_read else 0 in
259
260 (
261 match con.partial_in with
262 | HaveHdr partial_pkt ->
263 (* we complete the data *)
264 if sz > 0 then
265 Partial.append partial_pkt (Bytes.to_string b) sz;
266 if Partial.to_complete partial_pkt = 0 then (
267 let pkt = Packet.of_partialpkt partial_pkt in
268 con.partial_in <- init_partial_in ();
269 Some pkt
270 ) else None
271 | NoHdr (i, buf) ->
272 (* we complete the partial header *)
273 if sz > 0 then
274 Bytes.blit b 0 buf (Partial.header_size () - i) sz;
275 con.partial_in <- if sz = i then
276 HaveHdr (Partial.of_string (Bytes.to_string buf)) else NoHdr (i - sz, buf);
277 None
278 )
279
280 let classify t =
281 match t.Packet.ty with
282 | Op.Watchevent -> Watchevent
283 | _ -> CommandReply
284
285 let newcon ~capacity backend =
286 let limit = function
287 | CommandReply -> capacity.maxoutstanding
288 | Watchevent -> capacity.maxwatchevents
289 in
290 {
291 backend = backend;
292 pkt_out = Queue.create ~capacity:(capacity.maxoutstanding + capacity.maxwatchevents) ~classify ~limit;
293 partial_in = init_partial_in ();
294 partial_out = "";
295 capacity = capacity;
296 }
297
298 let open_fd fd = newcon (Fd { fd = fd; })
299
300 let open_mmap mmap notifyfct =
301 (* Advertise XENSTORE_SERVER_FEATURE_RECONNECTION *)
302 Xs_ring.set_server_features mmap (Xs_ring.Server_features.singleton Xs_ring.Server_feature.Reconnection);
303 newcon (Xenmmap {
304 mmap = mmap;
305 eventchn_notify = notifyfct;
306 work_again = false; })
307
308 let close con =
309 match con.backend with
310 | Fd backend -> Unix.close backend.fd
311 | Xenmmap backend -> Xenmmap.unmap backend.mmap
312
313 let is_fd con =
314 match con.backend with
315 | Fd _ -> true
316 | Xenmmap _ -> false
317
318 let is_mmap con = not (is_fd con)
319
320 let output_len con = Queue.length con.pkt_out
321 let has_new_output con = Queue.length con.pkt_out > 0
322 let has_old_output con = String.length con.partial_out > 0
323
324 let has_output con = has_new_output con || has_old_output con
325
326 let peek_output con = Queue.peek con.pkt_out
327
328 let has_partial_input con = match con.partial_in with
329 | HaveHdr _ -> true
330 | NoHdr (n, _) -> n < Partial.header_size ()
331 let has_more_input con =
332 match con.backend with
333 | Fd _ -> false
334 | Xenmmap backend -> backend.work_again
335
336 let is_selectable con =
337 match con.backend with
338 | Fd _ -> true
339 | Xenmmap _ -> false
340
341 let get_fd con =
342 match con.backend with
343 | Fd backend -> backend.fd
344 | Xenmmap _ -> raise (Failure "get_fd")