+static
+void deferred_free_viewer_stream(struct rcu_head *head)
+{
+ struct relay_viewer_stream *stream =
+ caa_container_of(head, struct relay_viewer_stream, rcu_node);
+
+ free(stream->path_name);
+ free(stream->channel_name);
+ free(stream);
+}
+
+static
+void delete_viewer_stream(struct relay_viewer_stream *vstream)
+{
+ int delret;
+ struct lttng_ht_iter iter;
+
+ iter.iter.node = &vstream->stream_n.node;
+ delret = lttng_ht_del(viewer_streams_ht, &iter);
+ assert(!delret);
+}
+
+static
+void destroy_viewer_stream(struct relay_viewer_stream *vstream)
+{
+ unsigned long ret_ref;
+ int ret;
+
+ assert(vstream);
+ ret_ref = uatomic_add_return(&vstream->ctf_trace->refcount, -1);
+ assert(ret_ref >= 0);
+
+ if (vstream->read_fd >= 0) {
+ ret = close(vstream->read_fd);
+ if (ret < 0) {
+ PERROR("close read_fd");
+ }
+ }
+ if (vstream->index_read_fd >= 0) {
+ ret = close(vstream->index_read_fd);
+ if (ret < 0) {
+ PERROR("close index_read_fd");
+ }
+ }
+
+ /*
+ * If the only stream left in the HT is the metadata stream,
+ * we need to remove it because we won't detect a EOF for this
+ * stream.
+ */
+ if (ret_ref == 1 && vstream->ctf_trace->viewer_metadata_stream) {
+ delete_viewer_stream(vstream->ctf_trace->viewer_metadata_stream);
+ destroy_viewer_stream(vstream->ctf_trace->viewer_metadata_stream);
+ vstream->ctf_trace->metadata_stream = NULL;
+ DBG("Freeing ctf_trace %" PRIu64, vstream->ctf_trace->id);
+ /*
+ * The streaming-side is already closed and we can't receive a new
+ * stream concurrently at this point (since the session is being
+ * destroyed), so when we detect the refcount equals 0, we are the
+ * only owners of the ctf_trace and we can free it ourself.
+ */
+ free(vstream->ctf_trace);
+ }
+
+ call_rcu(&vstream->rcu_node, deferred_free_viewer_stream);
+}
+