Debian Codegraph @

device-src/xfer-dest-taper-splitter.c

raw
1 /*
2 * Amanda, The Advanced Maryland Automatic Network Disk Archiver
3 * Copyright (c) 2009-2012 Zmanda, Inc. All Rights Reserved.
4 * Copyright (c) 2013-2016 Carbonite, Inc. All Rights Reserved.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 *
20 * Contact information: Carbonite Inc., 756 N Pastoria Ave
21 * Sunnyvale, CA 94085, or: http://www.zmanda.com
22 */
23
24 #include "amanda.h"
25 #include "amxfer.h"
26 #include "xfer-device.h"
27 #include "conffile.h"
28 #include "device.h"
29
30 /* A transfer destination that writes an entire dumpfile to one or more files
31 * on one or more devices, without any caching. This destination supports both
32 * LEOM-based splitting (in which parts are never rewound) and cache_inform-based
33 * splitting (in which rewound parts are read from holding disk). */
34
35 /*
36 * File Slices - Cache Information
37 *
38 * The cache_inform implementation adds cache information to a linked list of
39 * these objects, in order. The objects are arranged in a linked list, and
40 * describe the files in which the part data is stored. Note that we assume
41 * that slices are added *before* they are needed: the xfer element will fail
42 * if it tries to rewind and does not find a suitable slice.
43 *
44 * The slices should be "fast forwarded" after every part, so that the first
45 * byte in part_slices is the first byte of the part; when a retry of a part is
46 * required, use the iterator methods to properly open the various files and do
47 * the buffering.
48 */
49
50 typedef struct FileSlice {
51 struct FileSlice *next;
52
53 /* fully-qualified filename to read from (or NULL to read from
54 * disk_cache_read_fd in XferDestTaperCacher) */
55 char *filename;
56
57 /* offset in file to start at */
58 guint64 offset;
59
60 /* length of data to read */
61 guint64 length;
62 } FileSlice;
63
64 /*
65 * Xfer Dest Taper
66 */
67
68 static GObjectClass *parent_class = NULL;
69
70 typedef struct XferDestTaperSplitter {
71 XferDestTaper __parent__;
72
73 /* object parameters
74 *
75 * These values are supplied to the constructor, and can be assumed
76 * constant for the lifetime of the element.
77 */
78
79 /* Maximum size of each part (bytes) */
80 guint64 part_size;
81
82 /* the device's need for streaming (it's assumed that all subsequent devices
83 * have the same needs) */
84 StreamingRequirement streaming;
85
86 /* block size expected by the target device */
87 gsize block_size;
88
89 /* TRUE if this element is expecting slices via cache_inform */
90 gboolean expect_cache_inform;
91
92 /* The thread doing the actual writes to tape; this also handles buffering
93 * for streaming */
94 GThread *device_thread;
95
96 /* Ring Buffer */
97 GMutex *ring_mutex;
98 GCond *ring_cond;
99 mem_ring_t *mem_ring;
100 gboolean ring_ready;
101
102 /* Element State
103 *
104 * "state" includes all of the variables below (including device
105 * parameters). Note that the device_thread holdes this mutex for the
106 * entire duration of writing a part.
107 *
108 * state_mutex should always be locked before mem_ring->mutex, if both are to be
109 * held simultaneously.
110 */
111 GMutex *state_mutex;
112 GCond *state_cond;
113 volatile gboolean paused;
114
115 /* The device to write to, and the header to write to it */
116 Device *volatile device;
117 dumpfile_t *volatile part_header;
118
119 /* bytes to read from cached slices before reading from the ring buffer */
120 guint64 bytes_to_read_from_slices;
121 guint64 max_memory;
122
123 /* part number in progress */
124 volatile guint64 partnum;
125
126 /* status of the last part */
127 gboolean last_part_eof;
128 gboolean last_part_eom;
129 gboolean last_part_successful;
130
131 /* true if the element is done writing to devices */
132 gboolean no_more_parts;
133
134 /* total bytes written in the current part */
135 volatile guint64 part_bytes_written;
136
137 /* The list of active slices for the current part. The cache_inform method
138 * appends to this list. It is safe to read this linked list, beginning at
139 * the head, *if* you can guarantee that slices will not be fast-forwarded
140 * in the interim. The finalize method for this class will take care of
141 * freeing any leftover slices. Take the part_slices mutex while modifying
142 * the links in this list. */
143 FileSlice *part_slices;
144 GMutex *part_slices_mutex;
145
146 crc_t crc_before_part;
147 int more_space;
148
149 } XferDestTaperSplitter;
150
151 static DeviceWriteResult retry_write(XferDestTaperSplitter *self, gsize to_write,
152 gpointer buf);
153
154 static GType xfer_dest_taper_splitter_get_type(void);
155 #define XFER_DEST_TAPER_SPLITTER_TYPE (xfer_dest_taper_splitter_get_type())
156 #define XFER_DEST_TAPER_SPLITTER(obj) G_TYPE_CHECK_INSTANCE_CAST((obj), xfer_dest_taper_splitter_get_type(), XferDestTaperSplitter)
157 #define XFER_DEST_TAPER_SPLITTER_CONST(obj) G_TYPE_CHECK_INSTANCE_CAST((obj), xfer_dest_taper_splitter_get_type(), XferDestTaperSplitter const)
158 #define XFER_DEST_TAPER_SPLITTER_CLASS(klass) G_TYPE_CHECK_CLASS_CAST((klass), xfer_dest_taper_splitter_get_type(), XferDestTaperSplitterClass)
159 #define IS_XFER_DEST_TAPER_SPLITTER(obj) G_TYPE_CHECK_INSTANCE_TYPE((obj), xfer_dest_taper_splitter_get_type ())
160 #define XFER_DEST_TAPER_SPLITTER_GET_CLASS(obj) G_TYPE_INSTANCE_GET_CLASS((obj), xfer_dest_taper_splitter_get_type(), XferDestTaperSplitterClass)
161
162 typedef struct {
163 XferDestTaperClass __parent__;
164
165 } XferDestTaperSplitterClass;
166
167 /*
168 * Debug logging
169 */
170
171 #define DBG(LEVEL, ...) if (debug_taper >= LEVEL) { _xdt_dbg(__VA_ARGS__); }
172 static void
173 _xdt_dbg(const char *fmt, ...)
174 {
175 va_list argp;
176 char msg[1024];
177
178 arglist_start(argp, fmt);
179 g_vsnprintf(msg, sizeof(msg), fmt, argp);
180 arglist_end(argp);
181 g_debug("XDTS: %s", msg);
182 }
183
184 /* "Fast forward" the slice list by the given length. This will free any
185 * slices that are no longer necessary, and adjust the offset and length of the
186 * first remaining slice. This assumes the state mutex is locked during its
187 * operation.
188 *
189 * @param self: element
190 * @param length: number of bytes to fast forward
191 */
192 static void
193 fast_forward_slices(
194 XferDestTaperSplitter *self,
195 guint64 length)
196 {
197 FileSlice *slice;
198
199 /* consume slices until we've eaten the whole part */
200 g_mutex_lock(self->part_slices_mutex);
201 while (length > 0) {
202 g_assert(self->part_slices);
203 slice = self->part_slices;
204
205 if (slice->length <= length) {
206 length -= slice->length;
207
208 self->part_slices = slice->next;
209 if (slice->filename)
210 g_free(slice->filename);
211 g_free(slice);
212 slice = self->part_slices;
213 } else {
214 slice->length -= length;
215 slice->offset += length;
216 break;
217 }
218 }
219 g_mutex_unlock(self->part_slices_mutex);
220 }
221
222 /*
223 * Slice Iterator
224 */
225
226 /* A struct for use in iterating over data in the slices */
227 typedef struct SliceIterator {
228 /* current slice */
229 FileSlice *slice;
230
231 /* file descriptor of the current file, or -1 if it's not open yet */
232 int cur_fd;
233
234 /* bytes remaining in this slice */
235 guint64 slice_remaining;
236 } SliceIterator;
237
238 /* Utility functions for SliceIterator */
239
240 /* Begin iterating over slices, starting at the first byte of the first slice.
241 * Initializes a pre-allocated SliceIterator. The caller must ensure that
242 * fast_forward_slices is not called while an iteration is in
243 * progress.
244 */
245 static void
246 iterate_slices(
247 XferDestTaperSplitter *self,
248 SliceIterator *iter)
249 {
250 iter->cur_fd = -1;
251 iter->slice_remaining = 0;
252 g_mutex_lock(self->part_slices_mutex);
253 iter->slice = self->part_slices;
254 /* it's safe to unlock this because, at worst, a new entry will
255 * be appended while the iterator is in progress */
256 g_mutex_unlock(self->part_slices_mutex);
257 }
258
259
260 /* Get a block of data from the iterator, returning a pointer to a buffer
261 * containing the data; the buffer remains the property of the iterator.
262 * Returns NULL on error, after calling xfer_cancel_with_error with an
263 * appropriate error message. This function does not block, so it does not
264 * check for cancellation.
265 */
266 static gpointer
267 iterator_get_block(
268 XferDestTaperSplitter *self,
269 SliceIterator *iter,
270 gpointer buf,
271 gsize bytes_needed)
272 {
273 gsize buf_offset = 0;
274 XferElement *elt = XFER_ELEMENT(self);
275
276 g_assert(iter != NULL);
277 g_assert(buf != NULL);
278
279 while (bytes_needed > 0) {
280 gsize read_size;
281 gsize bytes_read;
282
283 if (iter->cur_fd < 0) {
284 guint64 offset;
285
286 g_assert(iter->slice != NULL);
287 g_assert(iter->slice->filename != NULL);
288
289 iter->cur_fd = open(iter->slice->filename, O_RDONLY, 0);
290 if (iter->cur_fd < 0) {
291 xfer_cancel_with_error(elt,
292 _("Could not open '%s' for reading: %s"),
293 iter->slice->filename, strerror(errno));
294 return NULL;
295 }
296
297 iter->slice_remaining = iter->slice->length;
298 offset = iter->slice->offset;
299
300 if (lseek(iter->cur_fd, offset, SEEK_SET) == -1) {
301 xfer_cancel_with_error(elt,
302 _("Could not seek '%s' for reading: %s"),
303 iter->slice->filename, strerror(errno));
304 return NULL;
305 }
306 }
307
308 read_size = MIN(iter->slice_remaining, bytes_needed);
309 bytes_read = read_fully(iter->cur_fd, (gchar *)buf + buf_offset, read_size,
310 NULL);
311 if (bytes_read < read_size) {
312 xfer_cancel_with_error(elt, _("Error reading '%s': %s"),
313 iter->slice->filename,
314 errno ? strerror(errno) : _("Unexpected EOF"));
315 return NULL;
316 }
317
318 iter->slice_remaining -= bytes_read;
319 buf_offset += bytes_read;
320 bytes_needed -= bytes_read;
321
322 if (iter->slice_remaining <= 0) {
323 if (close(iter->cur_fd) < 0) {
324 xfer_cancel_with_error(elt,
325 _("Could not close fd %d: %s"),
326 iter->cur_fd, strerror(errno));
327 return NULL;
328 }
329 iter->cur_fd = -1;
330
331 iter->slice = iter->slice->next;
332
333 if (elt->cancelled)
334 return NULL;
335 }
336 }
337
338 return buf;
339 }
340
341
342 /* Free the iterator's resources */
343 static void
344 iterator_free(
345 SliceIterator *iter)
346 {
347 if (iter->cur_fd >= 0)
348 close(iter->cur_fd);
349 }
350
351 /*
352 * Device Thread
353 */
354
355 /* Wait for at least one block, or EOF, to be available in the ring buffer.
356 * Called with the ring mutex held. */
357 static gsize
358 device_thread_wait_for_block(
359 XferDestTaperSplitter *self,
360 gboolean *eof_flag)
361 {
362 XferElement *elt = XFER_ELEMENT(self);
363 gsize bytes_needed = self->device->block_size;
364 gsize usable = 0;
365
366 *eof_flag = FALSE;
367
368 if (self->mem_ring) {
369 gsize max_ring_block_size = MAX(self->mem_ring->producer_block_size,
370 self->mem_ring->consumer_block_size);
371
372 /* for any kind of streaming, we need to fill the entire buffer before the
373 * first byte */
374 if (self->part_bytes_written == 0 && self->streaming != STREAMING_REQUIREMENT_NONE)
375 bytes_needed = self->mem_ring->ring_size - max_ring_block_size;
376
377 while (1) {
378 /* are we ready? */
379 if (elt->cancelled)
380 break;
381
382 usable = self->mem_ring->written - self->mem_ring->readx;
383 *eof_flag = self->mem_ring->eof_flag;
384 if (usable >= bytes_needed) {
385 break;
386 }
387
388 if (self->mem_ring->eof_flag)
389 break;
390
391 /* nope - so wait */
392 g_cond_wait(self->mem_ring->add_cond, self->mem_ring->mutex);
393
394 /* in STREAMING_REQUIREMENT_REQUIRED, once we decide to wait for more bytes,
395 * we need to wait for the entire buffer to fill */
396 if (self->streaming == STREAMING_REQUIREMENT_REQUIRED)
397 bytes_needed = self->mem_ring->ring_size - max_ring_block_size;
398 }
399
400 } else { // shm_ring
401 gsize max_ring_block_size = MAX(elt->shm_ring->mc->producer_block_size,
402 elt->shm_ring->mc->consumer_block_size);
403 if (self->part_bytes_written == 0 && self->streaming != STREAMING_REQUIREMENT_NONE)
404 bytes_needed = elt->shm_ring->ring_size - max_ring_block_size;
405
406 while (!elt->cancelled &&
407 !elt->shm_ring->mc->cancelled) {
408
409 if (shm_ring_sem_wait(elt->shm_ring, elt->shm_ring->sem_read) != 0)
410 break;
411 usable = elt->shm_ring->mc->written - elt->shm_ring->mc->readx;
412 *eof_flag = elt->shm_ring->mc->eof_flag;
413
414 if (elt->cancelled || elt->shm_ring->mc->cancelled)
415 break;
416
417 if (usable >= bytes_needed)
418 break;
419
420 if (*eof_flag)
421 break;
422
423
424 if (self->streaming == STREAMING_REQUIREMENT_REQUIRED)
425 bytes_needed = elt->shm_ring->ring_size - max_ring_block_size;
426 }
427 if (elt->shm_ring->mc->cancelled && !elt->cancelled) {
428 xfer_cancel_with_error(elt, "shm_ring_cancelled");
429 }
430 }
431 if (self->part_size)
432 usable = MIN(usable, self->part_size - self->part_bytes_written);
433
434 return usable;
435 }
436
437 /* Mark readx bytes as free in the ring buffer. Called with the ring mutex
438 * held. */
439 static void
440 device_thread_consume_block(
441 XferDestTaperSplitter *self,
442 gsize readx)
443 {
444 XferElement *elt = XFER_ELEMENT(self);
445 uint64_t read_offset;
446
447 if (self->mem_ring) {
448 read_offset = self->mem_ring->read_offset + readx;
449 if (read_offset >= self->mem_ring->ring_size)
450 read_offset -= self->mem_ring->ring_size;
451 self->mem_ring->readx += readx;
452 self->mem_ring->read_offset = read_offset;
453 g_cond_broadcast(self->mem_ring->free_cond);
454 } else { // shm_ring
455 read_offset = elt->shm_ring->mc->read_offset + readx;
456 if (read_offset >= elt->shm_ring->ring_size)
457 read_offset -= elt->shm_ring->ring_size;
458 elt->shm_ring->mc->readx += readx;
459 elt->shm_ring->mc->read_offset = read_offset;
460 sem_post(elt->shm_ring->sem_write);
461 }
462 }
463
464 /* Write an entire part. Called with the state_mutex held */
465 static XMsg *
466 device_thread_write_part(
467 XferDestTaperSplitter *self)
468 {
469 GTimer *timer = g_timer_new();
470 XferElement *elt = XFER_ELEMENT(self);
471
472 enum { PART_EOF, PART_LEOM, PART_EOP, PART_FAILED } part_status = PART_FAILED;
473 int fileno = 0;
474 XMsg *msg;
475 void *buf;
476
477 self->part_bytes_written = 0;
478 self->crc_before_part = elt->crc;
479
480 g_timer_start(timer);
481
482 /* write the header; if this fails or hits LEOM, we consider this a
483 * successful 0-byte part */
484 if (!device_start_file(self->device, self->part_header) || self->device->is_eom) {
485 part_status = PART_LEOM;
486 goto part_done;
487 }
488
489 fileno = self->device->file;
490 g_assert(fileno > 0);
491
492 /* free the header, now that it's written */
493 dumpfile_free(self->part_header);
494 self->part_header = NULL;
495
496 /* First, read the requisite number of bytes from the part_slices, if the part was
497 * unsuccessful. */
498 if (self->bytes_to_read_from_slices) {
499 SliceIterator iter;
500 gsize to_write = self->block_size;
501 gpointer buf = g_malloc(to_write);
502 gboolean successful = TRUE;
503 guint64 bytes_from_slices = self->bytes_to_read_from_slices;
504
505 DBG(5, "reading %ju bytes from slices", (uintmax_t)bytes_from_slices);
506
507 iterate_slices(self, &iter);
508 while (bytes_from_slices) {
509 DeviceWriteResult ok;
510
511 if (!iterator_get_block(self, &iter, buf, to_write)) {
512 part_status = PART_FAILED;
513 successful = FALSE;
514 break;
515 }
516
517 /* note that it's OK to reference these ring_* vars here, as they
518 * are static at this point */
519 ok = device_write_block(self->device, (guint)to_write, buf);
520 DBG(8, "writing %ju bytes from slice to device", (uintmax_t)to_write);
521
522 if (ok == WRITE_SPACE)
523 ok = retry_write(self, to_write, buf);
524
525 if (ok == WRITE_FAILED) {
526 part_status = PART_FAILED;
527 successful = FALSE;
528 break;
529 } else if (ok == WRITE_FULL) {
530 part_status = PART_EOP;
531 successful = FALSE;
532 break;
533 } else if (ok == WRITE_SPACE) {
534 part_status = PART_EOP;
535 successful = FALSE;
536 break;
537 }
538
539 self->part_bytes_written += to_write;
540 bytes_from_slices -= to_write;
541 crc32_add((uint8_t *)buf, to_write, &elt->crc);
542
543 if (self->part_size && self->part_bytes_written >= self->part_size) {
544 part_status = PART_EOP;
545 successful = FALSE;
546 break;
547 } else if (self->device->is_eom) {
548 part_status = PART_LEOM;
549 successful = FALSE;
550 break;
551 }
552 }
553
554 iterator_free(&iter);
555 g_free(buf);
556
557 /* if we didn't finish, get out of here now */
558 if (!successful)
559 goto part_done;
560 }
561
562 if (self->mem_ring)
563 g_mutex_lock(self->mem_ring->mutex);
564 while (!elt->cancelled &&
565 (!elt->shm_ring || !elt->shm_ring->mc->cancelled)) {
566 DeviceWriteResult ok;
567 gboolean eof_flag;
568
569 /* wait for at least one block, and (if necessary) prebuffer */
570 gsize to_writeX = device_thread_wait_for_block(self, &eof_flag);
571 if (elt->cancelled || (elt->shm_ring && elt->shm_ring->mc->cancelled))
572 break;
573
574 while (to_writeX >= self->device->block_size || eof_flag) {
575 //crc_t block_crc;
576 gsize to_write = MIN(to_writeX, self->device->block_size);
577 if (elt->cancelled)
578 goto part_done_unlock;
579
580 if (to_write == 0) {
581 part_status = PART_EOF;
582 goto part_done_unlock;
583 }
584
585 if (self->mem_ring)
586 g_mutex_unlock(self->mem_ring->mutex);
587 DBG(8, "writing %ju bytes to device", (uintmax_t)to_write);
588
589 /* note that it's OK to reference these ring_* vars here, as they
590 * are static at this point */
591 if (self->mem_ring) {
592 buf = self->mem_ring->buffer + self->mem_ring->read_offset;
593 } else {
594 buf = elt->shm_ring->data + elt->shm_ring->mc->read_offset;
595 }
596 ok = device_write_block(self->device, (guint)to_write, buf);
597
598 if (ok == WRITE_SPACE)
599 ok = retry_write(self, to_write, buf);
600
601 if (self->mem_ring)
602 g_mutex_lock(self->mem_ring->mutex);
603
604 if (ok == WRITE_FAILED) {
605 part_status = PART_FAILED;
606 goto part_done_unlock;
607 } else if (ok == WRITE_FULL) {
608 part_status = PART_EOP;
609 goto part_done_unlock;
610 } else if (ok == WRITE_SPACE) {
611 part_status = PART_EOP;
612 goto part_done_unlock;
613 }
614
615 crc32_add((uint8_t *)(buf),
616 to_write, &elt->crc);
617 self->part_bytes_written += to_write;
618 device_thread_consume_block(self, to_write);
619
620 if (self->part_size && self->part_bytes_written >= self->part_size) {
621 part_status = PART_EOP;
622 goto part_done_unlock;
623 } else if (self->device->is_eom) {
624 part_status = PART_LEOM;
625 goto part_done_unlock;
626 }
627 to_writeX -= to_write;
628 }
629 }
630 part_done_unlock:
631 if (self->mem_ring)
632 g_mutex_unlock(self->mem_ring->mutex);
633
634 part_done:
635 if (elt->shm_ring) {
636 if (elt->cancelled) {
637 if (elt->shm_ring) {
638 g_debug("device_thread_write_part: cancelling shm-ring because xfer is cancelled");
639 elt->shm_ring->mc->cancelled = TRUE;
640 }
641 } else if (elt->shm_ring->mc->cancelled) {
642 part_status = PART_FAILED;
643 xfer_cancel_with_error(elt, "shm_ring cancelled");
644 }
645 sem_post(elt->shm_ring->sem_read);
646 sem_post(elt->shm_ring->sem_read);
647 sem_post(elt->shm_ring->sem_read);
648 sem_post(elt->shm_ring->sem_write);
649 }
650 /* if we write all of the blocks, but the finish_file fails, then likely
651 * there was some buffering going on in the device driver, and the blocks
652 * did not all make it to permanent storage -- so it's a failed part. Note
653 * that we try to finish_file even if the part failed, just to be thorough. */
654 if (self->device->in_file) {
655 if (!device_finish_file(self->device)) {
656 if (!elt->cancelled) {
657 part_status = PART_FAILED;
658 }
659 }
660 }
661
662 g_timer_stop(timer);
663 if (part_status == PART_FAILED) {
664 elt->crc = self->crc_before_part;
665 }
666
667 msg = xmsg_new(XFER_ELEMENT(self), XMSG_PART_DONE, 0);
668 msg->size = self->part_bytes_written;
669 msg->duration = g_timer_elapsed(timer, NULL);
670 msg->partnum = self->partnum;
671 msg->fileno = fileno;
672 msg->successful = self->last_part_successful = part_status != PART_FAILED;
673 msg->eom = self->last_part_eom = part_status == PART_LEOM || self->device->is_eom;
674 msg->eof = self->last_part_eof = part_status == PART_EOF;
675
676 /* time runs backward on some test boxes, so make sure this is positive */
677 if (msg->duration < 0) msg->duration = 0;
678
679 if (msg->successful && msg->size > 0)
680 self->partnum++;
681 //self->no_more_parts = msg->eof || (!msg->successful && !self->expect_cache_inform);
682 self->no_more_parts = msg->eof;
683
684
685 g_timer_destroy(timer);
686
687 return msg;
688 }
689
690 static gpointer
691 device_thread(
692 gpointer data)
693 {
694 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(data);
695 XferElement *elt = XFER_ELEMENT(self);
696 XMsg *msg;
697
698 DBG(1, "(this is the device thread)");
699
700 if (elt->input_mech == XFER_MECH_PUSH_BUFFER) {
701 self->mem_ring = create_mem_ring();
702 init_mem_ring(self->mem_ring, self->max_memory, self->device->block_size);
703 } else if (elt->input_mech == XFER_MECH_MEM_RING) {
704 self->mem_ring = xfer_element_get_mem_ring(elt->upstream);
705 mem_ring_consumer_set_size(self->mem_ring, self->max_memory, self->device->block_size);
706 } else if (elt->input_mech == XFER_MECH_SHM_RING) {
707 shm_ring_consumer_set_size(elt->shm_ring, self->max_memory, self->device->block_size);
708 if (elt->input_mech == XFER_MECH_SHM_RING &&
709 elt->shm_ring->mc->cancelled) {
710 g_debug("A shm_ring is cancelled");
711 if (!elt->cancelled) {
712 xfer_cancel_with_error(XFER_ELEMENT(self)->upstream,
713 _("failed to set shm-ring"));
714 }
715 goto device_thread_done;
716 }
717 }
718 crc32_init(&elt->crc);
719
720 /* This is the outer loop, that loops once for each split part written to
721 * tape. */
722 g_mutex_lock(self->ring_mutex);
723 self->ring_ready = TRUE;
724 g_cond_broadcast(self->ring_cond);
725 g_mutex_unlock(self->ring_mutex);
726 g_mutex_lock(self->state_mutex);
727 while (1) {
728 /* wait until the main thread un-pauses us, and check that we have
729 * the relevant device info available (block_size) */
730 while (self->paused && !elt->cancelled) {
731 DBG(9, "device_thread waiting to be unpaused");
732 g_cond_wait(self->state_cond, self->state_mutex);
733 }
734 DBG(9, "device_thread done waiting");
735
736 if (elt->cancelled)
737 break;
738
739 if (elt->input_mech == XFER_MECH_SHM_RING &&
740 elt->shm_ring->mc->cancelled) {
741 g_debug("B shm_ring is cancelled");
742 if (!elt->cancelled) {
743 xfer_cancel_with_error(XFER_ELEMENT(self)->upstream,
744 _("shm-ring cancelled"));
745 }
746 break;
747 }
748
749 DBG(2, "device_thread beginning to write part");
750 msg = device_thread_write_part(self);
751 DBG(2, "device_thread done writing part");
752
753 if (!msg) /* cancelled */
754 break;
755
756 /* release the slices for this part, if there were any slices */
757 if (msg->successful && self->expect_cache_inform) {
758 fast_forward_slices(self, msg->size);
759 }
760
761 xfer_queue_message(elt->xfer, msg);
762
763 /* pause ourselves and await instructions from the main thread */
764 self->paused = TRUE;
765
766 /* if this is the last part, we're done with the part loop */
767 if (self->no_more_parts)
768 break;
769 }
770 g_mutex_unlock(self->state_mutex);
771
772 // notify the producer that everythinng is read
773 if (elt->input_mech == XFER_MECH_SHM_RING) {
774 sem_post(elt->shm_ring->sem_write);
775 }
776
777 g_debug("device_thread sending XMSG_CRC message");
778 DBG(2, "xfer-dest-taper-splitter CRC: %08x size %lld",
779 crc32_finish(&elt->crc), (long long)elt->crc.size);
780 msg = xmsg_new(XFER_ELEMENT(self), XMSG_CRC, 0);
781 msg->crc = crc32_finish(&elt->crc);
782 msg->size = elt->crc.size;
783 xfer_queue_message(elt->xfer, msg);
784
785 device_thread_done:
786 /* tell the main thread we're done */
787 xfer_queue_message(XFER_ELEMENT(self)->xfer, xmsg_new(XFER_ELEMENT(self), XMSG_DONE, 0));
788
789 return NULL;
790 }
791
792 /*
793 * Class mechanics
794 */
795
796 static void
797 push_buffer_impl(
798 XferElement *elt,
799 gpointer buf,
800 size_t size)
801 {
802 XferDestTaperSplitter *self = (XferDestTaperSplitter *)elt;
803 gchar *p = buf;
804
805 DBG(3, "push_buffer(%p, %ju)", buf, (uintmax_t)size);
806
807 /* do nothing if cancelled */
808 if (G_UNLIKELY(elt->cancelled)) {
809 goto free_and_finish;
810 }
811
812 if (G_UNLIKELY(!self->ring_ready)) {
813 g_mutex_lock(self->ring_mutex);
814 while (!self->ring_ready && !elt->cancelled) {
815 g_cond_wait(self->ring_cond, self->ring_mutex);
816 }
817 if (elt->cancelled)
818 goto unlock_and_free_and_finish;
819 g_mutex_unlock(self->ring_mutex);
820 }
821
822 /* handle EOF */
823 if (G_UNLIKELY(buf == NULL)) {
824 /* indicate EOF to the device thread */
825 g_mutex_lock(self->mem_ring->mutex);
826 self->mem_ring->eof_flag = TRUE;
827 g_cond_broadcast(self->mem_ring->add_cond);
828 g_mutex_unlock(self->mem_ring->mutex);
829 goto free_and_finish;
830 }
831
832 /* push the block into the ring buffer, in pieces if necessary */
833 g_mutex_lock(self->mem_ring->mutex);
834 while (size > 0) {
835 gsize avail;
836
837 /* wait for some space */
838 while (self->mem_ring->written - self->mem_ring->readx == self->mem_ring->ring_size && !elt->cancelled) {
839 DBG(9, "push_buffer waiting for any space to buffer pushed data");
840 g_cond_wait(self->mem_ring->free_cond, self->mem_ring->mutex);
841 }
842 DBG(9, "push_buffer done waiting");
843
844 if (elt->cancelled)
845 goto unlock_and_free_and_finish;
846
847 /* only copy to the end of the buffer, if the available space wraps
848 * around to the beginning */
849 avail = MIN(size, self->mem_ring->ring_size - (self->mem_ring->written - self->mem_ring->readx));
850 avail = MIN(avail, self->mem_ring->ring_size - self->mem_ring->write_offset);
851
852 /* copy AVAIL bytes into the ring buf (knowing it's contiguous) */
853 memmove(self->mem_ring->buffer + self->mem_ring->write_offset, p, avail);
854
855 /* reset the ring variables to represent this state */
856 self->mem_ring->written += avail;
857 self->mem_ring->write_offset += avail; /* will, at most, hit mem_ring->ring_size */
858 if (self->mem_ring->write_offset == self->mem_ring->ring_size)
859 self->mem_ring->write_offset = 0;
860 p = (gpointer)((guchar *)p + avail);
861 size -= avail;
862
863 /* and give the device thread a notice that data is ready */
864 g_cond_broadcast(self->mem_ring->add_cond);
865 }
866
867 unlock_and_free_and_finish:
868 g_mutex_unlock(self->mem_ring->mutex);
869
870 free_and_finish:
871 if (buf)
872 g_free(buf);
873 }
874
875 /*
876 * Element mechanics
877 */
878
879 static gboolean
880 start_impl(
881 XferElement *elt)
882 {
883 XferDestTaperSplitter *self = (XferDestTaperSplitter *)elt;
884 GError *error = NULL;
885
886 self->device_thread = g_thread_create(device_thread, (gpointer)self, FALSE, &error);
887 if (!self->device_thread) {
888 g_critical(_("Error creating new thread: %s (%s)"),
889 error->message, errno? strerror(errno) : _("no error code"));
890 }
891
892 return TRUE;
893 }
894
895 static gboolean
896 cancel_impl(
897 XferElement *elt,
898 gboolean expect_eof)
899 {
900 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(elt);
901 gboolean rv;
902
903 /* chain up first */
904 rv = XFER_ELEMENT_CLASS(parent_class)->cancel(elt, expect_eof);
905
906 /* then signal all of our condition variables, so that threads waiting on them
907 * wake up and see elt->cancelled. */
908 g_mutex_lock(self->ring_mutex);
909 g_cond_broadcast(self->ring_cond);
910 g_mutex_unlock(self->ring_mutex);
911
912 if (elt->shm_ring && !elt->shm_ring->mc->cancelled) {
913 if (!elt->shm_ring->mc->cancelled) {
914 g_debug("XDTS:cancel_impl: cancelling shm-ring because xfer is cancelled");
915 elt->shm_ring->mc->cancelled = TRUE;
916 }
917 sem_post(elt->shm_ring->sem_ready);
918 sem_post(elt->shm_ring->sem_start);
919 sem_post(elt->shm_ring->sem_read);
920 sem_post(elt->shm_ring->sem_write);
921 }
922 if (self->mem_ring) {
923 g_mutex_lock(self->mem_ring->mutex);
924 self->mem_ring->eof_flag = TRUE;
925 g_cond_broadcast(self->mem_ring->add_cond);
926 g_cond_broadcast(self->mem_ring->free_cond);
927 g_mutex_unlock(self->mem_ring->mutex);
928 }
929
930 g_mutex_lock(self->state_mutex);
931 g_cond_broadcast(self->state_cond);
932 g_mutex_unlock(self->state_mutex);
933
934 return rv;
935 }
936
937 static void
938 start_part_impl(
939 XferDestTaper *xdt,
940 gboolean retry_part,
941 dumpfile_t *header)
942 {
943 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(xdt);
944 XferElement *elt = XFER_ELEMENT(self);
945
946 g_assert(self->device != NULL);
947 g_assert(!self->device->in_file);
948 g_assert(header != NULL);
949
950 DBG(1, "start_part() start_part_impl");
951
952 /* we can only retry the part if we're getting slices via cache_inform's */
953 if (retry_part) {
954 if (self->last_part_successful) {
955 xfer_cancel_with_error(XFER_ELEMENT(self),
956 _("Previous part did not fail; cannot retry"));
957 if (elt->shm_ring && !elt->shm_ring->mc->cancelled) {
958 elt->shm_ring->mc->cancelled = TRUE;
959 sem_post(elt->shm_ring->sem_ready);
960 sem_post(elt->shm_ring->sem_start);
961 sem_post(elt->shm_ring->sem_read);
962 sem_post(elt->shm_ring->sem_write);
963 }
964 return;
965 }
966
967 if (!self->expect_cache_inform) {
968 xfer_cancel_with_error(XFER_ELEMENT(self),
969 _("No cache for previous failed part; cannot retry"));
970 if (elt->shm_ring && !elt->shm_ring->mc->cancelled) {
971 elt->shm_ring->mc->cancelled = TRUE;
972 sem_post(elt->shm_ring->sem_ready);
973 sem_post(elt->shm_ring->sem_start);
974 sem_post(elt->shm_ring->sem_read);
975 sem_post(elt->shm_ring->sem_write);
976 }
977 return;
978 }
979
980 self->bytes_to_read_from_slices = self->part_bytes_written;
981 } else {
982 /* don't read any bytes from the slices, since we're not retrying */
983 self->bytes_to_read_from_slices = 0;
984 }
985
986 g_mutex_lock(self->state_mutex);
987 g_assert(self->paused);
988 g_assert(!self->no_more_parts);
989
990 if (self->part_header)
991 dumpfile_free(self->part_header);
992 self->part_header = dumpfile_copy(header);
993
994 DBG(1, "unpausing");
995 self->paused = FALSE;
996 g_cond_broadcast(self->state_cond);
997
998 g_mutex_unlock(self->state_mutex);
999 }
1000
1001 static void
1002 use_device_impl(
1003 XferDestTaper *xdtself,
1004 Device *device)
1005 {
1006 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(xdtself);
1007 StreamingRequirement newstreaming;
1008 GValue val;
1009
1010 DBG(1, "use_device(%s)%s", device->device_name, (device == self->device)? " (no change)":"");
1011
1012 /* short-circuit if nothing is changing */
1013 if (self->device == device)
1014 return;
1015
1016 g_mutex_lock(self->state_mutex);
1017 if (self->device)
1018 g_object_unref(self->device);
1019 self->device = device;
1020 g_object_ref(device);
1021
1022 /* get this new device's streaming requirements */
1023 bzero(&val, sizeof(val));
1024 if (!device_property_get(self->device, PROPERTY_STREAMING, &val)
1025 || !G_VALUE_HOLDS(&val, STREAMING_REQUIREMENT_TYPE)) {
1026 g_warning("Couldn't get streaming type for %s", self->device->device_name);
1027 } else {
1028 newstreaming = g_value_get_enum(&val);
1029 if (newstreaming != self->streaming)
1030 g_warning("New device has different streaming requirements from the original; "
1031 "ignoring new requirement");
1032 }
1033 g_value_unset(&val);
1034
1035 /* check that the blocksize hasn't changed */
1036 if (self->block_size != device->block_size) {
1037 g_mutex_unlock(self->state_mutex);
1038 xfer_cancel_with_error(XFER_ELEMENT(self),
1039 _("All devices used by the taper must have the same block size"));
1040 return;
1041 }
1042 g_mutex_unlock(self->state_mutex);
1043 }
1044
1045 static void
1046 cache_inform_impl(
1047 XferDestTaper *xdt,
1048 const char *filename,
1049 off_t offset,
1050 off_t length)
1051 {
1052 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(xdt);
1053 FileSlice *slice = g_new(FileSlice, 1), *iter;
1054
1055 slice->next = NULL;
1056 slice->filename = g_strdup(filename);
1057 slice->offset = offset;
1058 slice->length = length;
1059
1060 g_mutex_lock(self->part_slices_mutex);
1061 if (self->part_slices) {
1062 for (iter = self->part_slices; iter->next; iter = iter->next) {}
1063 iter->next = slice;
1064 } else {
1065 self->part_slices = slice;
1066 }
1067 g_mutex_unlock(self->part_slices_mutex);
1068 }
1069
1070 static guint64
1071 get_part_bytes_written_impl(
1072 XferDestTaper *xdtself)
1073 {
1074 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(xdtself);
1075
1076 /* NOTE: this access is unsafe and may return inconsistent results (e.g, a
1077 * partial write to the 64-bit value on a 32-bit system). This is ok for
1078 * the moment, as it's only informational, but be warned. */
1079 if (self->device) {
1080 return device_get_bytes_written(self->device);
1081 } else {
1082 return self->part_bytes_written;
1083 }
1084 }
1085
1086 static void
1087 new_space_available_impl(
1088 XferDestTaper *xdtself,
1089 int made_space)
1090 {
1091 XferDestTaperSplitter *self;
1092
1093 self = XFER_DEST_TAPER_SPLITTER(xdtself);
1094
1095 self->more_space = made_space;
1096 g_mutex_lock(self->state_mutex);
1097 device_reset(self->device);
1098 g_cond_broadcast(self->state_cond);
1099 g_mutex_unlock(self->state_mutex);
1100 }
1101 static void
1102 instance_init(
1103 XferElement *elt)
1104 {
1105 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(elt);
1106 elt->can_generate_eof = FALSE;
1107
1108 self->ring_mutex = g_mutex_new();
1109 self->ring_cond = g_cond_new();
1110 self->state_mutex = g_mutex_new();
1111 self->state_cond = g_cond_new();
1112 self->part_slices_mutex = g_mutex_new();
1113
1114 self->device = NULL;
1115 self->paused = TRUE;
1116 self->part_header = NULL;
1117 self->partnum = 1;
1118 self->part_bytes_written = 0;
1119 self->part_slices = NULL;
1120 crc32_init(&elt->crc);
1121 }
1122
1123 static gboolean
1124 setup_impl(
1125 XferElement *elt)
1126 {
1127 if (elt->input_mech == XFER_MECH_SHM_RING) {
1128 elt->shm_ring = shm_ring_create(NULL);
1129 }
1130
1131 return TRUE;
1132 }
1133
1134 static void
1135 finalize_impl(
1136 GObject * obj_self)
1137 {
1138 XferDestTaperSplitter *self = XFER_DEST_TAPER_SPLITTER(obj_self);
1139 XferElement *elt = XFER_ELEMENT(self);
1140 FileSlice *slice, *next_slice;
1141
1142 g_mutex_free(self->ring_mutex);
1143 g_cond_free(self->ring_cond);
1144 g_mutex_free(self->state_mutex);
1145 g_cond_free(self->state_cond);
1146
1147 if (self->mem_ring) {
1148 g_mutex_free(self->mem_ring->mutex);
1149 g_cond_free(self->mem_ring->add_cond);
1150 g_cond_free(self->mem_ring->free_cond);
1151 }
1152
1153 if (elt->shm_ring) {
1154 close_consumer_shm_ring(elt->shm_ring);
1155 elt->shm_ring = NULL;
1156 }
1157
1158 g_mutex_free(self->part_slices_mutex);
1159
1160 for (slice = self->part_slices; slice; slice = next_slice) {
1161 next_slice = slice->next;
1162 if (slice->filename)
1163 g_free(slice->filename);
1164 g_free(slice);
1165 }
1166
1167 if (self->mem_ring && self->mem_ring->buffer)
1168 g_free(self->mem_ring->buffer);
1169
1170 if (self->part_header)
1171 dumpfile_free(self->part_header);
1172
1173 if (self->device)
1174 g_object_unref(self->device);
1175
1176 /* chain up */
1177 G_OBJECT_CLASS(parent_class)->finalize(obj_self);
1178 }
1179
1180 static void
1181 class_init(
1182 XferDestTaperSplitterClass * selfc)
1183 {
1184 XferElementClass *klass = XFER_ELEMENT_CLASS(selfc);
1185 XferDestTaperClass *xdt_klass = XFER_DEST_TAPER_CLASS(selfc);
1186 GObjectClass *goc = G_OBJECT_CLASS(selfc);
1187 static xfer_element_mech_pair_t mech_pairs[] = {
1188 { XFER_MECH_PUSH_BUFFER, XFER_MECH_NONE, XFER_NROPS(2), XFER_NTHREADS(1), XFER_NALLOC(0) },
1189 { XFER_MECH_MEM_RING, XFER_MECH_NONE, XFER_NROPS(1), XFER_NTHREADS(2), XFER_NALLOC(1) },
1190 { XFER_MECH_SHM_RING, XFER_MECH_NONE, XFER_NROPS(1), XFER_NTHREADS(1), XFER_NALLOC(0) },
1191 { XFER_MECH_NONE, XFER_MECH_NONE, XFER_NROPS(0), XFER_NTHREADS(0), XFER_NALLOC(0) },
1192 };
1193
1194 klass->setup = setup_impl;
1195 klass->start = start_impl;
1196 klass->cancel = cancel_impl;
1197 klass->push_buffer = push_buffer_impl;
1198 xdt_klass->start_part = start_part_impl;
1199 xdt_klass->use_device = use_device_impl;
1200 xdt_klass->cache_inform = cache_inform_impl;
1201 xdt_klass->get_part_bytes_written = get_part_bytes_written_impl;
1202 xdt_klass->new_space_available = new_space_available_impl;
1203 goc->finalize = finalize_impl;
1204
1205 klass->perl_class = "Amanda::Xfer::Dest::Taper::Splitter";
1206 klass->mech_pairs = mech_pairs;
1207
1208 parent_class = g_type_class_peek_parent(selfc);
1209 }
1210
1211 static GType
1212 xfer_dest_taper_splitter_get_type (void)
1213 {
1214 static GType type = 0;
1215
1216 if (G_UNLIKELY(type == 0)) {
1217 static const GTypeInfo info = {
1218 sizeof (XferDestTaperSplitterClass),
1219 (GBaseInitFunc) NULL,
1220 (GBaseFinalizeFunc) NULL,
1221 (GClassInitFunc) class_init,
1222 (GClassFinalizeFunc) NULL,
1223 NULL /* class_data */,
1224 sizeof (XferDestTaperSplitter),
1225 0 /* n_preallocs */,
1226 (GInstanceInitFunc) instance_init,
1227 NULL
1228 };
1229
1230 type = g_type_register_static (XFER_DEST_TAPER_TYPE, "XferDestTaperSplitter", &info, 0);
1231 }
1232
1233 return type;
1234 }
1235
1236 /*
1237 * Constructor
1238 */
1239
1240 XferElement *
1241 xfer_dest_taper_splitter(
1242 Device *first_device,
1243 size_t max_memory,
1244 guint64 part_size,
1245 gboolean expect_cache_inform)
1246 {
1247 XferDestTaperSplitter *self = (XferDestTaperSplitter *)g_object_new(XFER_DEST_TAPER_SPLITTER_TYPE, NULL);
1248 GValue val;
1249
1250 /* max_memory and part_size get rounded up to the next multiple of
1251 * block_size */
1252 max_memory = ((max_memory + first_device->block_size - 1)
1253 / first_device->block_size) * first_device->block_size;
1254 if (part_size)
1255 part_size = ((part_size + first_device->block_size - 1)
1256 / first_device->block_size) * first_device->block_size;
1257
1258 self->part_size = part_size;
1259 self->partnum = 1;
1260 self->device = first_device;
1261
1262 g_object_ref(self->device);
1263 self->block_size = first_device->block_size;
1264 self->paused = TRUE;
1265 self->no_more_parts = FALSE;
1266
1267 self->max_memory = max_memory;
1268
1269 /* get this new device's streaming requirements */
1270 bzero(&val, sizeof(val));
1271 if (!device_property_get(self->device, PROPERTY_STREAMING, &val)
1272 || !G_VALUE_HOLDS(&val, STREAMING_REQUIREMENT_TYPE)) {
1273 g_warning("Couldn't get streaming type for %s", self->device->device_name);
1274 self->streaming = STREAMING_REQUIREMENT_REQUIRED;
1275 } else {
1276 self->streaming = g_value_get_enum(&val);
1277 }
1278 g_value_unset(&val);
1279
1280 /* grab data from cache_inform, just in case we hit PEOM */
1281 self->expect_cache_inform = expect_cache_inform;
1282
1283 return XFER_ELEMENT(self);
1284 }
1285
1286 static DeviceWriteResult
1287 retry_write(
1288 XferDestTaperSplitter *self,
1289 gsize to_write,
1290 gpointer buf)
1291 {
1292 XferElement *elt = XFER_ELEMENT(self);
1293 XMsg *msg;
1294 DeviceWriteResult result;
1295
1296 msg = xmsg_new(XFER_ELEMENT(self), XMSG_NO_SPACE, 0);
1297 xfer_queue_message(elt->xfer, msg);
1298
1299 while(1) {
1300 self->more_space = -1;
1301 while (self->more_space == -1 && !elt->cancelled) {
1302 g_cond_wait(self->state_cond, self->state_mutex);
1303 }
1304
1305 if (elt->cancelled) {
1306 return WRITE_FAILED;
1307 }
1308
1309 result = device_write_block(self->device, (guint)to_write, buf);
1310 if (result != WRITE_SPACE) {
1311 return result; /* WRITE_SUCCEED, WRITE_FAILED or WRITE_FULL */
1312 }
1313 if (self->more_space == 0) {
1314 return result; /* WRITE_SPACE */
1315 }
1316 }
1317 }
1318