+ /* Check if subbuf was fully written. This is from Mathieu's algorithm/paper. */
+ /* FIXME: not sure data_size = 0xffffffff when the buffer is not full. It might
+ * take the value of the header size initially */
+ if (((commit_seq - buf->subbuf_size) & commit_seq_mask)
+ - (USTD_BUFFER_TRUNC(consumed_offset, buf) >> n_subbufs_order) == 0
+ && header->data_size != 0xffffffff && header->sb_size != 0xffffffff) {
+ /* If it was, we only check the data_size. This is the amount of valid data at
+ * the beginning of the subbuffer. */
+ valid_length = header->data_size;
+ }
+ else {
+ /* If the subbuffer was not fully written, then we don't check data_size because
+ * it hasn't been written yet. Instead we check commit_seq and use it to choose
+ * a value for data_size. The viewer will need this value when parsing.
+ */
+
+ valid_length = commit_seq & (buf->subbuf_size-1);
+ header->data_size = valid_length;
+ header->sb_size = PAGE_ALIGN(valid_length);
+ assert(i_subbuf == (last_subbuf % buf->n_subbufs));
+ }
+
+
+ patient_write(buf->file_fd, buf->mem + i_subbuf * buf->subbuf_size, valid_length);
+
+ /* pad with empty bytes */
+ pad_size = PAGE_ALIGN(valid_length)-valid_length;
+ if(pad_size) {
+ tmp = malloc(pad_size);
+ memset(tmp, 0, pad_size);
+ patient_write(buf->file_fd, tmp, pad_size);
+ free(tmp);
+ }