+ return ret;
+}
+
+/*
+ * Atomically check if new streams got added in the session since the last
+ * check and reset the flag to 0.
+ *
+ * Returns 1 if new streams got added, 0 if nothing changed, a negative value
+ * on error.
+ */
+static
+int check_new_streams(uint64_t session_id, struct lttng_ht *sessions_ht)
+{
+ int ret;
+ unsigned long current_val;
+ struct relay_session *session;
+
+ assert(sessions_ht);
+
+ session = session_find_by_id(sessions_ht, session_id);
+ if (!session) {
+ DBG("Relay session %" PRIu64 " not found", session_id);
+ ret = -1;
+ goto error;
+ }
+
+ current_val = uatomic_cmpxchg(&session->new_streams, 1, 0);
+ ret = current_val;
+
+error:
+ return ret;
+}
+
+/*
+ * Send viewer streams to the given socket. The ignore_sent_flag indicates if
+ * this function should ignore the sent flag or not.
+ *
+ * Return 0 on success or else a negative value.
+ */
+static
+ssize_t send_viewer_streams(struct lttcomm_sock *sock,
+ struct relay_session *session, unsigned int ignore_sent_flag)
+{
+ ssize_t ret;
+ struct lttng_viewer_stream send_stream;
+ struct lttng_ht_iter iter;
+ struct relay_viewer_stream *vstream;
+
+ assert(session);
+
+ rcu_read_lock();
+
+ cds_lfht_for_each_entry(viewer_streams_ht->ht, &iter.iter, vstream,
+ stream_n.node) {
+ struct ctf_trace *ctf_trace;
+
+ health_code_update();
+
+ /* Ignore if not the same session. */
+ if (vstream->session_id != session->id ||
+ (!ignore_sent_flag && vstream->sent_flag)) {
+ continue;
+ }
+
+ ctf_trace = ctf_trace_find_by_path(session->ctf_traces_ht,
+ vstream->path_name);
+ assert(ctf_trace);
+
+ send_stream.id = htobe64(vstream->stream_handle);
+ send_stream.ctf_trace_id = htobe64(ctf_trace->id);
+ send_stream.metadata_flag = htobe32(vstream->metadata_flag);
+ strncpy(send_stream.path_name, vstream->path_name,
+ sizeof(send_stream.path_name));
+ strncpy(send_stream.channel_name, vstream->channel_name,
+ sizeof(send_stream.channel_name));
+
+ DBG("Sending stream %" PRIu64 " to viewer", vstream->stream_handle);
+ ret = send_response(sock, &send_stream, sizeof(send_stream));
+ if (ret < 0) {
+ goto end_unlock;
+ }
+ vstream->sent_flag = 1;
+ }
+
+ ret = 0;
+
+end_unlock:
+ rcu_read_unlock();
+ return ret;