+ if (seek_last && viewer_stream->index_read_fd > 0) {
+ ret = lseek(viewer_stream->index_read_fd,
+ viewer_stream->total_index_received *
+ sizeof(struct lttng_packet_index),
+ SEEK_CUR);
+ if (ret < 0) {
+ goto error;
+ }
+ viewer_stream->last_sent_index =
+ viewer_stream->total_index_received;
+ }
+
+ ret = 0;
+
+error:
+ return ret;
+}
+
+/*
+ * Rotate a stream to the next tracefile.
+ *
+ * Returns 0 on success, 1 on EOF, a negative value on error.
+ */
+static
+int rotate_viewer_stream(struct relay_viewer_stream *viewer_stream,
+ struct relay_stream *stream)
+{
+ int ret;
+ uint64_t tracefile_id;
+
+ assert(viewer_stream);
+
+ tracefile_id = (viewer_stream->tracefile_count_current + 1) %
+ viewer_stream->tracefile_count;
+ /*
+ * Detect the last tracefile to open.
+ */
+ if (viewer_stream->tracefile_count_last != -1ULL &&
+ viewer_stream->tracefile_count_last ==
+ viewer_stream->tracefile_count_current) {
+ ret = 1;
+ goto end;
+ }
+
+ if (stream) {
+ pthread_mutex_lock(&stream->viewer_stream_rotation_lock);
+ }
+ /*
+ * The writer and the reader are not working in the same
+ * tracefile, we can read up to EOF, we don't care about the
+ * total_index_received.
+ */
+ if (!stream || (stream->tracefile_count_current != tracefile_id)) {
+ viewer_stream->close_write_flag = 1;
+ } else {
+ /*
+ * We are opening a file that is still open in write, make
+ * sure we limit our reading to the number of indexes
+ * received.
+ */
+ viewer_stream->close_write_flag = 0;
+ if (stream) {
+ viewer_stream->total_index_received =
+ stream->total_index_received;
+ }
+ }
+ viewer_stream->tracefile_count_current = tracefile_id;
+
+ ret = close(viewer_stream->index_read_fd);
+ if (ret < 0) {
+ PERROR("close index file %d",
+ viewer_stream->index_read_fd);
+ }
+ viewer_stream->index_read_fd = -1;
+ ret = close(viewer_stream->read_fd);
+ if (ret < 0) {
+ PERROR("close tracefile %d",
+ viewer_stream->read_fd);
+ }
+ viewer_stream->read_fd = -1;
+
+ pthread_mutex_lock(&viewer_stream->overwrite_lock);
+ viewer_stream->abort_flag = 0;
+ pthread_mutex_unlock(&viewer_stream->overwrite_lock);
+
+ viewer_stream->index_read_fd = -1;
+ viewer_stream->read_fd = -1;
+
+ if (stream) {
+ pthread_mutex_unlock(&stream->viewer_stream_rotation_lock);
+ }
+ ret = open_index(viewer_stream);
+ if (ret < 0) {
+ goto error;
+ }