1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (c) 2010 Red Hat, Inc. All Rights Reserved.
8 #include "xfs_format.h"
9 #include "xfs_log_format.h"
10 #include "xfs_shared.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_extent_busy.h"
14 #include "xfs_trans.h"
15 #include "xfs_trans_priv.h"
17 #include "xfs_log_priv.h"
18 #include "xfs_trace.h"
20 struct workqueue_struct *xfs_discard_wq;
23 * Allocate a new ticket. Failing to get a new ticket makes it really hard to
24 * recover, so we don't allow failure here. Also, we allocate in a context that
25 * we don't want to be issuing transactions from, so we need to tell the
26 * allocation code this as well.
28 * We don't reserve any space for the ticket - we are going to steal whatever
29 * space we require from transactions as they commit. To ensure we reserve all
30 * the space required, we need to set the current reservation of the ticket to
31 * zero so that we know to steal the initial transaction overhead from the
32 * first transaction commit.
34 static struct xlog_ticket *
35 xlog_cil_ticket_alloc(
38 struct xlog_ticket *tic;
40 tic = xlog_ticket_alloc(log, 0, 1, XFS_TRANSACTION, 0);
43 * set the current reservation to zero so we know to steal the basic
44 * transaction overhead reservation from the first transaction commit.
51 * Unavoidable forward declaration - xlog_cil_push_work() calls
52 * xlog_cil_ctx_alloc() itself.
54 static void xlog_cil_push_work(struct work_struct *work);
56 static struct xfs_cil_ctx *
57 xlog_cil_ctx_alloc(void)
59 struct xfs_cil_ctx *ctx;
61 ctx = kmem_zalloc(sizeof(*ctx), KM_NOFS);
62 INIT_LIST_HEAD(&ctx->committing);
63 INIT_LIST_HEAD(&ctx->busy_extents);
64 INIT_WORK(&ctx->push_work, xlog_cil_push_work);
71 struct xfs_cil_ctx *ctx)
73 ctx->sequence = ++cil->xc_current_sequence;
79 * After the first stage of log recovery is done, we know where the head and
80 * tail of the log are. We need this log initialisation done before we can
81 * initialise the first CIL checkpoint context.
83 * Here we allocate a log ticket to track space usage during a CIL push. This
84 * ticket is passed to xlog_write() directly so that we don't slowly leak log
85 * space by failing to account for space used by log headers and additional
86 * region headers for split regions.
89 xlog_cil_init_post_recovery(
92 log->l_cilp->xc_ctx->ticket = xlog_cil_ticket_alloc(log);
93 log->l_cilp->xc_ctx->sequence = 1;
100 return round_up((sizeof(struct xfs_log_vec) +
101 niovecs * sizeof(struct xfs_log_iovec)),
106 * shadow buffers can be large, so we need to use kvmalloc() here to ensure
107 * success. Unfortunately, kvmalloc() only allows GFP_KERNEL contexts to fall
108 * back to vmalloc, so we can't actually do anything useful with gfp flags to
109 * control the kmalloc() behaviour within kvmalloc(). Hence kmalloc() will do
110 * direct reclaim and compaction in the slow path, both of which are
111 * horrendously expensive. We just want kmalloc to fail fast and fall back to
112 * vmalloc if it can't get somethign straight away from the free lists or buddy
113 * allocator. Hence we have to open code kvmalloc outselves here.
115 * Also, we are in memalloc_nofs_save task context here, so despite the use of
116 * GFP_KERNEL here, we are actually going to be doing GFP_NOFS allocations. This
117 * is actually the only way to make vmalloc() do GFP_NOFS allocations, so lets
118 * just all pretend this is a GFP_KERNEL context operation....
124 gfp_t flags = GFP_KERNEL;
127 flags &= ~__GFP_DIRECT_RECLAIM;
128 flags |= __GFP_NOWARN | __GFP_NORETRY;
130 p = kmalloc(buf_size, flags);
132 p = vmalloc(buf_size);
139 * Allocate or pin log vector buffers for CIL insertion.
141 * The CIL currently uses disposable buffers for copying a snapshot of the
142 * modified items into the log during a push. The biggest problem with this is
143 * the requirement to allocate the disposable buffer during the commit if:
144 * a) does not exist; or
147 * If we do this allocation within xlog_cil_insert_format_items(), it is done
148 * under the xc_ctx_lock, which means that a CIL push cannot occur during
149 * the memory allocation. This means that we have a potential deadlock situation
150 * under low memory conditions when we have lots of dirty metadata pinned in
151 * the CIL and we need a CIL commit to occur to free memory.
153 * To avoid this, we need to move the memory allocation outside the
154 * xc_ctx_lock, but because the log vector buffers are disposable, that opens
155 * up a TOCTOU race condition w.r.t. the CIL committing and removing the log
156 * vector buffers between the check and the formatting of the item into the
157 * log vector buffer within the xc_ctx_lock.
159 * Because the log vector buffer needs to be unchanged during the CIL push
160 * process, we cannot share the buffer between the transaction commit (which
161 * modifies the buffer) and the CIL push context that is writing the changes
162 * into the log. This means skipping preallocation of buffer space is
163 * unreliable, but we most definitely do not want to be allocating and freeing
164 * buffers unnecessarily during commits when overwrites can be done safely.
166 * The simplest solution to this problem is to allocate a shadow buffer when a
167 * log item is committed for the second time, and then to only use this buffer
168 * if necessary. The buffer can remain attached to the log item until such time
169 * it is needed, and this is the buffer that is reallocated to match the size of
170 * the incoming modification. Then during the formatting of the item we can swap
171 * the active buffer with the new one if we can't reuse the existing buffer. We
172 * don't free the old buffer as it may be reused on the next modification if
173 * it's size is right, otherwise we'll free and reallocate it at that point.
175 * This function builds a vector for the changes in each log item in the
176 * transaction. It then works out the length of the buffer needed for each log
177 * item, allocates them and attaches the vector to the log item in preparation
178 * for the formatting step which occurs under the xc_ctx_lock.
180 * While this means the memory footprint goes up, it avoids the repeated
181 * alloc/free pattern that repeated modifications of an item would otherwise
182 * cause, and hence minimises the CPU overhead of such behaviour.
185 xlog_cil_alloc_shadow_bufs(
187 struct xfs_trans *tp)
189 struct xfs_log_item *lip;
191 list_for_each_entry(lip, &tp->t_items, li_trans) {
192 struct xfs_log_vec *lv;
196 bool ordered = false;
198 /* Skip items which aren't dirty in this transaction. */
199 if (!test_bit(XFS_LI_DIRTY, &lip->li_flags))
202 /* get number of vecs and size of data to be stored */
203 lip->li_ops->iop_size(lip, &niovecs, &nbytes);
206 * Ordered items need to be tracked but we do not wish to write
207 * them. We need a logvec to track the object, but we do not
208 * need an iovec or buffer to be allocated for copying data.
210 if (niovecs == XFS_LOG_VEC_ORDERED) {
217 * We 64-bit align the length of each iovec so that the start
218 * of the next one is naturally aligned. We'll need to
219 * account for that slack space here. Then round nbytes up
220 * to 64-bit alignment so that the initial buffer alignment is
221 * easy to calculate and verify.
223 nbytes += niovecs * sizeof(uint64_t);
224 nbytes = round_up(nbytes, sizeof(uint64_t));
227 * The data buffer needs to start 64-bit aligned, so round up
228 * that space to ensure we can align it appropriately and not
229 * overrun the buffer.
231 buf_size = nbytes + xlog_cil_iovec_space(niovecs);
234 * if we have no shadow buffer, or it is too small, we need to
237 if (!lip->li_lv_shadow ||
238 buf_size > lip->li_lv_shadow->lv_size) {
240 * We free and allocate here as a realloc would copy
241 * unnecessary data. We don't use kvzalloc() for the
242 * same reason - we don't need to zero the data area in
243 * the buffer, only the log vector header and the iovec
246 kmem_free(lip->li_lv_shadow);
247 lv = xlog_cil_kvmalloc(buf_size);
249 memset(lv, 0, xlog_cil_iovec_space(niovecs));
252 lv->lv_size = buf_size;
254 lv->lv_buf_len = XFS_LOG_VEC_ORDERED;
256 lv->lv_iovecp = (struct xfs_log_iovec *)&lv[1];
257 lip->li_lv_shadow = lv;
259 /* same or smaller, optimise common overwrite case */
260 lv = lip->li_lv_shadow;
262 lv->lv_buf_len = XFS_LOG_VEC_ORDERED;
269 /* Ensure the lv is set up according to ->iop_size */
270 lv->lv_niovecs = niovecs;
272 /* The allocated data region lies beyond the iovec region */
273 lv->lv_buf = (char *)lv + xlog_cil_iovec_space(niovecs);
279 * Prepare the log item for insertion into the CIL. Calculate the difference in
280 * log space and vectors it will consume, and if it is a new item pin it as
284 xfs_cil_prepare_item(
286 struct xfs_log_vec *lv,
287 struct xfs_log_vec *old_lv,
291 /* Account for the new LV being passed in */
292 if (lv->lv_buf_len != XFS_LOG_VEC_ORDERED) {
293 *diff_len += lv->lv_bytes;
294 *diff_iovecs += lv->lv_niovecs;
298 * If there is no old LV, this is the first time we've seen the item in
299 * this CIL context and so we need to pin it. If we are replacing the
300 * old_lv, then remove the space it accounts for and make it the shadow
301 * buffer for later freeing. In both cases we are now switching to the
302 * shadow buffer, so update the pointer to it appropriately.
305 if (lv->lv_item->li_ops->iop_pin)
306 lv->lv_item->li_ops->iop_pin(lv->lv_item);
307 lv->lv_item->li_lv_shadow = NULL;
308 } else if (old_lv != lv) {
309 ASSERT(lv->lv_buf_len != XFS_LOG_VEC_ORDERED);
311 *diff_len -= old_lv->lv_bytes;
312 *diff_iovecs -= old_lv->lv_niovecs;
313 lv->lv_item->li_lv_shadow = old_lv;
316 /* attach new log vector to log item */
317 lv->lv_item->li_lv = lv;
320 * If this is the first time the item is being committed to the
321 * CIL, store the sequence number on the log item so we can
322 * tell in future commits whether this is the first checkpoint
323 * the item is being committed into.
325 if (!lv->lv_item->li_seq)
326 lv->lv_item->li_seq = log->l_cilp->xc_ctx->sequence;
330 * Format log item into a flat buffers
332 * For delayed logging, we need to hold a formatted buffer containing all the
333 * changes on the log item. This enables us to relog the item in memory and
334 * write it out asynchronously without needing to relock the object that was
335 * modified at the time it gets written into the iclog.
337 * This function takes the prepared log vectors attached to each log item, and
338 * formats the changes into the log vector buffer. The buffer it uses is
339 * dependent on the current state of the vector in the CIL - the shadow lv is
340 * guaranteed to be large enough for the current modification, but we will only
341 * use that if we can't reuse the existing lv. If we can't reuse the existing
342 * lv, then simple swap it out for the shadow lv. We don't free it - that is
343 * done lazily either by th enext modification or the freeing of the log item.
345 * We don't set up region headers during this process; we simply copy the
346 * regions into the flat buffer. We can do this because we still have to do a
347 * formatting step to write the regions into the iclog buffer. Writing the
348 * ophdrs during the iclog write means that we can support splitting large
349 * regions across iclog boundares without needing a change in the format of the
350 * item/region encapsulation.
352 * Hence what we need to do now is change the rewrite the vector array to point
353 * to the copied region inside the buffer we just allocated. This allows us to
354 * format the regions into the iclog as though they are being formatted
355 * directly out of the objects themselves.
358 xlog_cil_insert_format_items(
360 struct xfs_trans *tp,
364 struct xfs_log_item *lip;
367 /* Bail out if we didn't find a log item. */
368 if (list_empty(&tp->t_items)) {
373 list_for_each_entry(lip, &tp->t_items, li_trans) {
374 struct xfs_log_vec *lv;
375 struct xfs_log_vec *old_lv = NULL;
376 struct xfs_log_vec *shadow;
377 bool ordered = false;
379 /* Skip items which aren't dirty in this transaction. */
380 if (!test_bit(XFS_LI_DIRTY, &lip->li_flags))
384 * The formatting size information is already attached to
385 * the shadow lv on the log item.
387 shadow = lip->li_lv_shadow;
388 if (shadow->lv_buf_len == XFS_LOG_VEC_ORDERED)
391 /* Skip items that do not have any vectors for writing */
392 if (!shadow->lv_niovecs && !ordered)
395 /* compare to existing item size */
397 if (lip->li_lv && shadow->lv_size <= lip->li_lv->lv_size) {
398 /* same or smaller, optimise common overwrite case */
406 * set the item up as though it is a new insertion so
407 * that the space reservation accounting is correct.
409 *diff_iovecs -= lv->lv_niovecs;
410 *diff_len -= lv->lv_bytes;
412 /* Ensure the lv is set up according to ->iop_size */
413 lv->lv_niovecs = shadow->lv_niovecs;
415 /* reset the lv buffer information for new formatting */
418 lv->lv_buf = (char *)lv +
419 xlog_cil_iovec_space(lv->lv_niovecs);
421 /* switch to shadow buffer! */
425 /* track as an ordered logvec */
426 ASSERT(lip->li_lv == NULL);
431 ASSERT(IS_ALIGNED((unsigned long)lv->lv_buf, sizeof(uint64_t)));
432 lip->li_ops->iop_format(lip, lv);
434 xfs_cil_prepare_item(log, lv, old_lv, diff_len, diff_iovecs);
439 * Insert the log items into the CIL and calculate the difference in space
440 * consumed by the item. Add the space to the checkpoint ticket and calculate
441 * if the change requires additional log metadata. If it does, take that space
442 * as well. Remove the amount of space we added to the checkpoint ticket from
443 * the current transaction ticket so that the accounting works out correctly.
446 xlog_cil_insert_items(
448 struct xfs_trans *tp)
450 struct xfs_cil *cil = log->l_cilp;
451 struct xfs_cil_ctx *ctx = cil->xc_ctx;
452 struct xfs_log_item *lip;
456 int iovhdr_res = 0, split_res = 0, ctx_res = 0;
461 * We can do this safely because the context can't checkpoint until we
462 * are done so it doesn't matter exactly how we update the CIL.
464 xlog_cil_insert_format_items(log, tp, &len, &diff_iovecs);
466 spin_lock(&cil->xc_cil_lock);
468 /* account for space used by new iovec headers */
469 iovhdr_res = diff_iovecs * sizeof(xlog_op_header_t);
471 ctx->nvecs += diff_iovecs;
473 /* attach the transaction to the CIL if it has any busy extents */
474 if (!list_empty(&tp->t_busy))
475 list_splice_init(&tp->t_busy, &ctx->busy_extents);
478 * Now transfer enough transaction reservation to the context ticket
479 * for the checkpoint. The context ticket is special - the unit
480 * reservation has to grow as well as the current reservation as we
481 * steal from tickets so we can correctly determine the space used
482 * during the transaction commit.
484 if (ctx->ticket->t_curr_res == 0) {
485 ctx_res = ctx->ticket->t_unit_res;
486 ctx->ticket->t_curr_res = ctx_res;
487 tp->t_ticket->t_curr_res -= ctx_res;
490 /* do we need space for more log record headers? */
491 iclog_space = log->l_iclog_size - log->l_iclog_hsize;
492 if (len > 0 && (ctx->space_used / iclog_space !=
493 (ctx->space_used + len) / iclog_space)) {
494 split_res = (len + iclog_space - 1) / iclog_space;
495 /* need to take into account split region headers, too */
496 split_res *= log->l_iclog_hsize + sizeof(struct xlog_op_header);
497 ctx->ticket->t_unit_res += split_res;
498 ctx->ticket->t_curr_res += split_res;
499 tp->t_ticket->t_curr_res -= split_res;
500 ASSERT(tp->t_ticket->t_curr_res >= len);
502 tp->t_ticket->t_curr_res -= len;
503 ctx->space_used += len;
506 * If we've overrun the reservation, dump the tx details before we move
507 * the log items. Shutdown is imminent...
509 if (WARN_ON(tp->t_ticket->t_curr_res < 0)) {
510 xfs_warn(log->l_mp, "Transaction log reservation overrun:");
512 " log items: %d bytes (iov hdrs: %d bytes)",
514 xfs_warn(log->l_mp, " split region headers: %d bytes",
516 xfs_warn(log->l_mp, " ctx ticket: %d bytes", ctx_res);
517 xlog_print_trans(tp);
521 * Now (re-)position everything modified at the tail of the CIL.
522 * We do this here so we only need to take the CIL lock once during
523 * the transaction commit.
525 list_for_each_entry(lip, &tp->t_items, li_trans) {
527 /* Skip items which aren't dirty in this transaction. */
528 if (!test_bit(XFS_LI_DIRTY, &lip->li_flags))
532 * Only move the item if it isn't already at the tail. This is
533 * to prevent a transient list_empty() state when reinserting
534 * an item that is already the only item in the CIL.
536 if (!list_is_last(&lip->li_cil, &cil->xc_cil))
537 list_move_tail(&lip->li_cil, &cil->xc_cil);
540 spin_unlock(&cil->xc_cil_lock);
542 if (tp->t_ticket->t_curr_res < 0)
543 xfs_force_shutdown(log->l_mp, SHUTDOWN_LOG_IO_ERROR);
547 xlog_cil_free_logvec(
548 struct xfs_log_vec *log_vector)
550 struct xfs_log_vec *lv;
552 for (lv = log_vector; lv; ) {
553 struct xfs_log_vec *next = lv->lv_next;
560 xlog_discard_endio_work(
561 struct work_struct *work)
563 struct xfs_cil_ctx *ctx =
564 container_of(work, struct xfs_cil_ctx, discard_endio_work);
565 struct xfs_mount *mp = ctx->cil->xc_log->l_mp;
567 xfs_extent_busy_clear(mp, &ctx->busy_extents, false);
572 * Queue up the actual completion to a thread to avoid IRQ-safe locking for
573 * pagb_lock. Note that we need a unbounded workqueue, otherwise we might
574 * get the execution delayed up to 30 seconds for weird reasons.
580 struct xfs_cil_ctx *ctx = bio->bi_private;
582 INIT_WORK(&ctx->discard_endio_work, xlog_discard_endio_work);
583 queue_work(xfs_discard_wq, &ctx->discard_endio_work);
588 xlog_discard_busy_extents(
589 struct xfs_mount *mp,
590 struct xfs_cil_ctx *ctx)
592 struct list_head *list = &ctx->busy_extents;
593 struct xfs_extent_busy *busyp;
594 struct bio *bio = NULL;
595 struct blk_plug plug;
598 ASSERT(xfs_has_discard(mp));
600 blk_start_plug(&plug);
601 list_for_each_entry(busyp, list, list) {
602 trace_xfs_discard_extent(mp, busyp->agno, busyp->bno,
605 error = __blkdev_issue_discard(mp->m_ddev_targp->bt_bdev,
606 XFS_AGB_TO_DADDR(mp, busyp->agno, busyp->bno),
607 XFS_FSB_TO_BB(mp, busyp->length),
609 if (error && error != -EOPNOTSUPP) {
611 "discard failed for extent [0x%llx,%u], error %d",
612 (unsigned long long)busyp->bno,
620 bio->bi_private = ctx;
621 bio->bi_end_io = xlog_discard_endio;
624 xlog_discard_endio_work(&ctx->discard_endio_work);
626 blk_finish_plug(&plug);
630 * Mark all items committed and clear busy extents. We free the log vector
631 * chains in a separate pass so that we unpin the log items as quickly as
636 struct xfs_cil_ctx *ctx)
638 struct xfs_mount *mp = ctx->cil->xc_log->l_mp;
639 bool abort = xlog_is_shutdown(ctx->cil->xc_log);
642 * If the I/O failed, we're aborting the commit and already shutdown.
643 * Wake any commit waiters before aborting the log items so we don't
644 * block async log pushers on callbacks. Async log pushers explicitly do
645 * not wait on log force completion because they may be holding locks
646 * required to unpin items.
649 spin_lock(&ctx->cil->xc_push_lock);
650 wake_up_all(&ctx->cil->xc_start_wait);
651 wake_up_all(&ctx->cil->xc_commit_wait);
652 spin_unlock(&ctx->cil->xc_push_lock);
655 xfs_trans_committed_bulk(ctx->cil->xc_log->l_ailp, ctx->lv_chain,
656 ctx->start_lsn, abort);
658 xfs_extent_busy_sort(&ctx->busy_extents);
659 xfs_extent_busy_clear(mp, &ctx->busy_extents,
660 xfs_has_discard(mp) && !abort);
662 spin_lock(&ctx->cil->xc_push_lock);
663 list_del(&ctx->committing);
664 spin_unlock(&ctx->cil->xc_push_lock);
666 xlog_cil_free_logvec(ctx->lv_chain);
668 if (!list_empty(&ctx->busy_extents))
669 xlog_discard_busy_extents(mp, ctx);
675 xlog_cil_process_committed(
676 struct list_head *list)
678 struct xfs_cil_ctx *ctx;
680 while ((ctx = list_first_entry_or_null(list,
681 struct xfs_cil_ctx, iclog_entry))) {
682 list_del(&ctx->iclog_entry);
683 xlog_cil_committed(ctx);
688 * Record the LSN of the iclog we were just granted space to start writing into.
689 * If the context doesn't have a start_lsn recorded, then this iclog will
690 * contain the start record for the checkpoint. Otherwise this write contains
691 * the commit record for the checkpoint.
694 xlog_cil_set_ctx_write_state(
695 struct xfs_cil_ctx *ctx,
696 struct xlog_in_core *iclog)
698 struct xfs_cil *cil = ctx->cil;
699 xfs_lsn_t lsn = be64_to_cpu(iclog->ic_header.h_lsn);
701 ASSERT(!ctx->commit_lsn);
702 if (!ctx->start_lsn) {
703 spin_lock(&cil->xc_push_lock);
705 * The LSN we need to pass to the log items on transaction
706 * commit is the LSN reported by the first log vector write, not
707 * the commit lsn. If we use the commit record lsn then we can
708 * move the tail beyond the grant write head.
710 ctx->start_lsn = lsn;
711 wake_up_all(&cil->xc_start_wait);
712 spin_unlock(&cil->xc_push_lock);
717 * Take a reference to the iclog for the context so that we still hold
718 * it when xlog_write is done and has released it. This means the
719 * context controls when the iclog is released for IO.
721 atomic_inc(&iclog->ic_refcnt);
724 * xlog_state_get_iclog_space() guarantees there is enough space in the
725 * iclog for an entire commit record, so we can attach the context
726 * callbacks now. This needs to be done before we make the commit_lsn
727 * visible to waiters so that checkpoints with commit records in the
728 * same iclog order their IO completion callbacks in the same order that
729 * the commit records appear in the iclog.
731 spin_lock(&cil->xc_log->l_icloglock);
732 list_add_tail(&ctx->iclog_entry, &iclog->ic_callbacks);
733 spin_unlock(&cil->xc_log->l_icloglock);
736 * Now we can record the commit LSN and wake anyone waiting for this
737 * sequence to have the ordered commit record assigned to a physical
738 * location in the log.
740 spin_lock(&cil->xc_push_lock);
741 ctx->commit_iclog = iclog;
742 ctx->commit_lsn = lsn;
743 wake_up_all(&cil->xc_commit_wait);
744 spin_unlock(&cil->xc_push_lock);
749 * Ensure that the order of log writes follows checkpoint sequence order. This
750 * relies on the context LSN being zero until the log write has guaranteed the
751 * LSN that the log write will start at via xlog_state_get_iclog_space().
759 xlog_cil_order_write(
762 enum _record_type record)
764 struct xfs_cil_ctx *ctx;
767 spin_lock(&cil->xc_push_lock);
768 list_for_each_entry(ctx, &cil->xc_committing, committing) {
770 * Avoid getting stuck in this loop because we were woken by the
771 * shutdown, but then went back to sleep once already in the
774 if (xlog_is_shutdown(cil->xc_log)) {
775 spin_unlock(&cil->xc_push_lock);
780 * Higher sequences will wait for this one so skip them.
781 * Don't wait for our own sequence, either.
783 if (ctx->sequence >= sequence)
786 /* Wait until the LSN for the record has been recorded. */
789 if (!ctx->start_lsn) {
790 xlog_wait(&cil->xc_start_wait, &cil->xc_push_lock);
795 if (!ctx->commit_lsn) {
796 xlog_wait(&cil->xc_commit_wait, &cil->xc_push_lock);
802 spin_unlock(&cil->xc_push_lock);
807 * Write out the log vector change now attached to the CIL context. This will
808 * write a start record that needs to be strictly ordered in ascending CIL
809 * sequence order so that log recovery will always use in-order start LSNs when
810 * replaying checkpoints.
813 xlog_cil_write_chain(
814 struct xfs_cil_ctx *ctx,
815 struct xfs_log_vec *chain)
817 struct xlog *log = ctx->cil->xc_log;
820 error = xlog_cil_order_write(ctx->cil, ctx->sequence, _START_RECORD);
823 return xlog_write(log, ctx, chain, ctx->ticket, XLOG_START_TRANS);
827 * Write out the commit record of a checkpoint transaction to close off a
828 * running log write. These commit records are strictly ordered in ascending CIL
829 * sequence order so that log recovery will always replay the checkpoints in the
833 xlog_cil_write_commit_record(
834 struct xfs_cil_ctx *ctx)
836 struct xlog *log = ctx->cil->xc_log;
837 struct xfs_log_iovec reg = {
840 .i_type = XLOG_REG_TYPE_COMMIT,
842 struct xfs_log_vec vec = {
848 if (xlog_is_shutdown(log))
851 error = xlog_cil_order_write(ctx->cil, ctx->sequence, _COMMIT_RECORD);
855 error = xlog_write(log, ctx, &vec, ctx->ticket, XLOG_COMMIT_TRANS);
857 xfs_force_shutdown(log->l_mp, SHUTDOWN_LOG_IO_ERROR);
862 * Push the Committed Item List to the log.
864 * If the current sequence is the same as xc_push_seq we need to do a flush. If
865 * xc_push_seq is less than the current sequence, then it has already been
866 * flushed and we don't need to do anything - the caller will wait for it to
867 * complete if necessary.
869 * xc_push_seq is checked unlocked against the sequence number for a match.
870 * Hence we can allow log forces to run racily and not issue pushes for the
871 * same sequence twice. If we get a race between multiple pushes for the same
872 * sequence they will block on the first one and then abort, hence avoiding
877 struct work_struct *work)
879 struct xfs_cil_ctx *ctx =
880 container_of(work, struct xfs_cil_ctx, push_work);
881 struct xfs_cil *cil = ctx->cil;
882 struct xlog *log = cil->xc_log;
883 struct xfs_log_vec *lv;
884 struct xfs_cil_ctx *new_ctx;
885 struct xlog_ticket *tic;
888 struct xfs_trans_header thdr;
889 struct xfs_log_iovec lhdr;
890 struct xfs_log_vec lvhdr = { NULL };
891 xfs_lsn_t preflush_tail_lsn;
894 DECLARE_COMPLETION_ONSTACK(bdev_flush);
895 bool push_commit_stable;
897 new_ctx = xlog_cil_ctx_alloc();
898 new_ctx->ticket = xlog_cil_ticket_alloc(log);
900 down_write(&cil->xc_ctx_lock);
902 spin_lock(&cil->xc_push_lock);
903 push_seq = cil->xc_push_seq;
904 ASSERT(push_seq <= ctx->sequence);
905 push_commit_stable = cil->xc_push_commit_stable;
906 cil->xc_push_commit_stable = false;
909 * As we are about to switch to a new, empty CIL context, we no longer
910 * need to throttle tasks on CIL space overruns. Wake any waiters that
911 * the hard push throttle may have caught so they can start committing
912 * to the new context. The ctx->xc_push_lock provides the serialisation
913 * necessary for safely using the lockless waitqueue_active() check in
916 if (waitqueue_active(&cil->xc_push_wait))
917 wake_up_all(&cil->xc_push_wait);
920 * Check if we've anything to push. If there is nothing, then we don't
921 * move on to a new sequence number and so we have to be able to push
922 * this sequence again later.
924 if (list_empty(&cil->xc_cil)) {
925 cil->xc_push_seq = 0;
926 spin_unlock(&cil->xc_push_lock);
931 /* check for a previously pushed sequence */
932 if (push_seq < ctx->sequence) {
933 spin_unlock(&cil->xc_push_lock);
938 * We are now going to push this context, so add it to the committing
939 * list before we do anything else. This ensures that anyone waiting on
940 * this push can easily detect the difference between a "push in
941 * progress" and "CIL is empty, nothing to do".
943 * IOWs, a wait loop can now check for:
944 * the current sequence not being found on the committing list;
946 * an unchanged sequence number
947 * to detect a push that had nothing to do and therefore does not need
948 * waiting on. If the CIL is not empty, we get put on the committing
949 * list before emptying the CIL and bumping the sequence number. Hence
950 * an empty CIL and an unchanged sequence number means we jumped out
951 * above after doing nothing.
953 * Hence the waiter will either find the commit sequence on the
954 * committing list or the sequence number will be unchanged and the CIL
955 * still dirty. In that latter case, the push has not yet started, and
956 * so the waiter will have to continue trying to check the CIL
957 * committing list until it is found. In extreme cases of delay, the
958 * sequence may fully commit between the attempts the wait makes to wait
959 * on the commit sequence.
961 list_add(&ctx->committing, &cil->xc_committing);
962 spin_unlock(&cil->xc_push_lock);
965 * The CIL is stable at this point - nothing new will be added to it
966 * because we hold the flush lock exclusively. Hence we can now issue
967 * a cache flush to ensure all the completed metadata in the journal we
968 * are about to overwrite is on stable storage.
970 * Because we are issuing this cache flush before we've written the
971 * tail lsn to the iclog, we can have metadata IO completions move the
972 * tail forwards between the completion of this flush and the iclog
973 * being written. In this case, we need to re-issue the cache flush
974 * before the iclog write. To detect whether the log tail moves, sample
975 * the tail LSN *before* we issue the flush.
977 preflush_tail_lsn = atomic64_read(&log->l_tail_lsn);
978 xfs_flush_bdev_async(&bio, log->l_mp->m_ddev_targp->bt_bdev,
982 * Pull all the log vectors off the items in the CIL, and remove the
983 * items from the CIL. We don't need the CIL lock here because it's only
984 * needed on the transaction commit side which is currently locked out
989 while (!list_empty(&cil->xc_cil)) {
990 struct xfs_log_item *item;
992 item = list_first_entry(&cil->xc_cil,
993 struct xfs_log_item, li_cil);
994 list_del_init(&item->li_cil);
996 ctx->lv_chain = item->li_lv;
998 lv->lv_next = item->li_lv;
1001 num_iovecs += lv->lv_niovecs;
1005 * Switch the contexts so we can drop the context lock and move out
1006 * of a shared context. We can't just go straight to the commit record,
1007 * though - we need to synchronise with previous and future commits so
1008 * that the commit records are correctly ordered in the log to ensure
1009 * that we process items during log IO completion in the correct order.
1011 * For example, if we get an EFI in one checkpoint and the EFD in the
1012 * next (e.g. due to log forces), we do not want the checkpoint with
1013 * the EFD to be committed before the checkpoint with the EFI. Hence
1014 * we must strictly order the commit records of the checkpoints so
1015 * that: a) the checkpoint callbacks are attached to the iclogs in the
1016 * correct order; and b) the checkpoints are replayed in correct order
1019 * Hence we need to add this context to the committing context list so
1020 * that higher sequences will wait for us to write out a commit record
1023 * xfs_log_force_seq requires us to mirror the new sequence into the cil
1024 * structure atomically with the addition of this sequence to the
1025 * committing list. This also ensures that we can do unlocked checks
1026 * against the current sequence in log forces without risking
1027 * deferencing a freed context pointer.
1029 spin_lock(&cil->xc_push_lock);
1030 xlog_cil_ctx_switch(cil, new_ctx);
1031 spin_unlock(&cil->xc_push_lock);
1032 up_write(&cil->xc_ctx_lock);
1035 * Build a checkpoint transaction header and write it to the log to
1036 * begin the transaction. We need to account for the space used by the
1037 * transaction header here as it is not accounted for in xlog_write().
1039 * The LSN we need to pass to the log items on transaction commit is
1040 * the LSN reported by the first log vector write. If we use the commit
1041 * record lsn then we can move the tail beyond the grant write head.
1044 thdr.th_magic = XFS_TRANS_HEADER_MAGIC;
1045 thdr.th_type = XFS_TRANS_CHECKPOINT;
1046 thdr.th_tid = tic->t_tid;
1047 thdr.th_num_items = num_iovecs;
1048 lhdr.i_addr = &thdr;
1049 lhdr.i_len = sizeof(xfs_trans_header_t);
1050 lhdr.i_type = XLOG_REG_TYPE_TRANSHDR;
1051 tic->t_curr_res -= lhdr.i_len + sizeof(xlog_op_header_t);
1053 lvhdr.lv_niovecs = 1;
1054 lvhdr.lv_iovecp = &lhdr;
1055 lvhdr.lv_next = ctx->lv_chain;
1058 * Before we format and submit the first iclog, we have to ensure that
1059 * the metadata writeback ordering cache flush is complete.
1061 wait_for_completion(&bdev_flush);
1063 error = xlog_cil_write_chain(ctx, &lvhdr);
1065 goto out_abort_free_ticket;
1067 error = xlog_cil_write_commit_record(ctx);
1069 goto out_abort_free_ticket;
1071 xfs_log_ticket_ungrant(log, tic);
1074 * If the checkpoint spans multiple iclogs, wait for all previous iclogs
1075 * to complete before we submit the commit_iclog. We can't use state
1076 * checks for this - ACTIVE can be either a past completed iclog or a
1077 * future iclog being filled, while WANT_SYNC through SYNC_DONE can be a
1078 * past or future iclog awaiting IO or ordered IO completion to be run.
1079 * In the latter case, if it's a future iclog and we wait on it, the we
1080 * will hang because it won't get processed through to ic_force_wait
1081 * wakeup until this commit_iclog is written to disk. Hence we use the
1082 * iclog header lsn and compare it to the commit lsn to determine if we
1083 * need to wait on iclogs or not.
1085 spin_lock(&log->l_icloglock);
1086 if (ctx->start_lsn != ctx->commit_lsn) {
1089 plsn = be64_to_cpu(ctx->commit_iclog->ic_prev->ic_header.h_lsn);
1090 if (plsn && XFS_LSN_CMP(plsn, ctx->commit_lsn) < 0) {
1092 * Waiting on ic_force_wait orders the completion of
1093 * iclogs older than ic_prev. Hence we only need to wait
1094 * on the most recent older iclog here.
1096 xlog_wait_on_iclog(ctx->commit_iclog->ic_prev);
1097 spin_lock(&log->l_icloglock);
1101 * We need to issue a pre-flush so that the ordering for this
1102 * checkpoint is correctly preserved down to stable storage.
1104 ctx->commit_iclog->ic_flags |= XLOG_ICL_NEED_FLUSH;
1108 * The commit iclog must be written to stable storage to guarantee
1109 * journal IO vs metadata writeback IO is correctly ordered on stable
1112 * If the push caller needs the commit to be immediately stable and the
1113 * commit_iclog is not yet marked as XLOG_STATE_WANT_SYNC to indicate it
1114 * will be written when released, switch it's state to WANT_SYNC right
1117 ctx->commit_iclog->ic_flags |= XLOG_ICL_NEED_FUA;
1118 if (push_commit_stable &&
1119 ctx->commit_iclog->ic_state == XLOG_STATE_ACTIVE)
1120 xlog_state_switch_iclogs(log, ctx->commit_iclog, 0);
1121 xlog_state_release_iclog(log, ctx->commit_iclog, preflush_tail_lsn);
1123 /* Not safe to reference ctx now! */
1125 spin_unlock(&log->l_icloglock);
1129 up_write(&cil->xc_ctx_lock);
1130 xfs_log_ticket_put(new_ctx->ticket);
1134 out_abort_free_ticket:
1135 xfs_log_ticket_ungrant(log, tic);
1136 ASSERT(xlog_is_shutdown(log));
1137 if (!ctx->commit_iclog) {
1138 xlog_cil_committed(ctx);
1141 spin_lock(&log->l_icloglock);
1142 xlog_state_release_iclog(log, ctx->commit_iclog, 0);
1143 /* Not safe to reference ctx now! */
1144 spin_unlock(&log->l_icloglock);
1148 * We need to push CIL every so often so we don't cache more than we can fit in
1149 * the log. The limit really is that a checkpoint can't be more than half the
1150 * log (the current checkpoint is not allowed to overwrite the previous
1151 * checkpoint), but commit latency and memory usage limit this to a smaller
1155 xlog_cil_push_background(
1156 struct xlog *log) __releases(cil->xc_ctx_lock)
1158 struct xfs_cil *cil = log->l_cilp;
1161 * The cil won't be empty because we are called while holding the
1162 * context lock so whatever we added to the CIL will still be there
1164 ASSERT(!list_empty(&cil->xc_cil));
1167 * Don't do a background push if we haven't used up all the
1168 * space available yet.
1170 if (cil->xc_ctx->space_used < XLOG_CIL_SPACE_LIMIT(log)) {
1171 up_read(&cil->xc_ctx_lock);
1175 spin_lock(&cil->xc_push_lock);
1176 if (cil->xc_push_seq < cil->xc_current_sequence) {
1177 cil->xc_push_seq = cil->xc_current_sequence;
1178 queue_work(cil->xc_push_wq, &cil->xc_ctx->push_work);
1182 * Drop the context lock now, we can't hold that if we need to sleep
1183 * because we are over the blocking threshold. The push_lock is still
1184 * held, so blocking threshold sleep/wakeup is still correctly
1187 up_read(&cil->xc_ctx_lock);
1190 * If we are well over the space limit, throttle the work that is being
1191 * done until the push work on this context has begun. Enforce the hard
1192 * throttle on all transaction commits once it has been activated, even
1193 * if the committing transactions have resulted in the space usage
1194 * dipping back down under the hard limit.
1196 * The ctx->xc_push_lock provides the serialisation necessary for safely
1197 * using the lockless waitqueue_active() check in this context.
1199 if (cil->xc_ctx->space_used >= XLOG_CIL_BLOCKING_SPACE_LIMIT(log) ||
1200 waitqueue_active(&cil->xc_push_wait)) {
1201 trace_xfs_log_cil_wait(log, cil->xc_ctx->ticket);
1202 ASSERT(cil->xc_ctx->space_used < log->l_logsize);
1203 xlog_wait(&cil->xc_push_wait, &cil->xc_push_lock);
1207 spin_unlock(&cil->xc_push_lock);
1212 * xlog_cil_push_now() is used to trigger an immediate CIL push to the sequence
1213 * number that is passed. When it returns, the work will be queued for
1214 * @push_seq, but it won't be completed.
1216 * If the caller is performing a synchronous force, we will flush the workqueue
1217 * to get previously queued work moving to minimise the wait time they will
1218 * undergo waiting for all outstanding pushes to complete. The caller is
1219 * expected to do the required waiting for push_seq to complete.
1221 * If the caller is performing an async push, we need to ensure that the
1222 * checkpoint is fully flushed out of the iclogs when we finish the push. If we
1223 * don't do this, then the commit record may remain sitting in memory in an
1224 * ACTIVE iclog. This then requires another full log force to push to disk,
1225 * which defeats the purpose of having an async, non-blocking CIL force
1226 * mechanism. Hence in this case we need to pass a flag to the push work to
1227 * indicate it needs to flush the commit record itself.
1235 struct xfs_cil *cil = log->l_cilp;
1240 ASSERT(push_seq && push_seq <= cil->xc_current_sequence);
1242 /* start on any pending background push to minimise wait time on it */
1244 flush_workqueue(cil->xc_push_wq);
1247 * If the CIL is empty or we've already pushed the sequence then
1248 * there's no work we need to do.
1250 spin_lock(&cil->xc_push_lock);
1251 if (list_empty(&cil->xc_cil) || push_seq <= cil->xc_push_seq) {
1252 spin_unlock(&cil->xc_push_lock);
1256 cil->xc_push_seq = push_seq;
1257 cil->xc_push_commit_stable = async;
1258 queue_work(cil->xc_push_wq, &cil->xc_ctx->push_work);
1259 spin_unlock(&cil->xc_push_lock);
1266 struct xfs_cil *cil = log->l_cilp;
1269 spin_lock(&cil->xc_push_lock);
1270 if (list_empty(&cil->xc_cil))
1272 spin_unlock(&cil->xc_push_lock);
1277 * Commit a transaction with the given vector to the Committed Item List.
1279 * To do this, we need to format the item, pin it in memory if required and
1280 * account for the space used by the transaction. Once we have done that we
1281 * need to release the unused reservation for the transaction, attach the
1282 * transaction to the checkpoint context so we carry the busy extents through
1283 * to checkpoint completion, and then unlock all the items in the transaction.
1285 * Called with the context lock already held in read mode to lock out
1286 * background commit, returns without it held once background commits are
1292 struct xfs_trans *tp,
1293 xfs_csn_t *commit_seq,
1296 struct xfs_cil *cil = log->l_cilp;
1297 struct xfs_log_item *lip, *next;
1300 * Do all necessary memory allocation before we lock the CIL.
1301 * This ensures the allocation does not deadlock with a CIL
1302 * push in memory reclaim (e.g. from kswapd).
1304 xlog_cil_alloc_shadow_bufs(log, tp);
1306 /* lock out background commit */
1307 down_read(&cil->xc_ctx_lock);
1309 xlog_cil_insert_items(log, tp);
1311 if (regrant && !xlog_is_shutdown(log))
1312 xfs_log_ticket_regrant(log, tp->t_ticket);
1314 xfs_log_ticket_ungrant(log, tp->t_ticket);
1315 tp->t_ticket = NULL;
1316 xfs_trans_unreserve_and_mod_sb(tp);
1319 * Once all the items of the transaction have been copied to the CIL,
1320 * the items can be unlocked and possibly freed.
1322 * This needs to be done before we drop the CIL context lock because we
1323 * have to update state in the log items and unlock them before they go
1324 * to disk. If we don't, then the CIL checkpoint can race with us and
1325 * we can run checkpoint completion before we've updated and unlocked
1326 * the log items. This affects (at least) processing of stale buffers,
1329 trace_xfs_trans_commit_items(tp, _RET_IP_);
1330 list_for_each_entry_safe(lip, next, &tp->t_items, li_trans) {
1331 xfs_trans_del_item(lip);
1332 if (lip->li_ops->iop_committing)
1333 lip->li_ops->iop_committing(lip, cil->xc_ctx->sequence);
1336 *commit_seq = cil->xc_ctx->sequence;
1338 /* xlog_cil_push_background() releases cil->xc_ctx_lock */
1339 xlog_cil_push_background(log);
1343 * Flush the CIL to stable storage but don't wait for it to complete. This
1344 * requires the CIL push to ensure the commit record for the push hits the disk,
1345 * but otherwise is no different to a push done from a log force.
1351 xfs_csn_t seq = log->l_cilp->xc_current_sequence;
1353 trace_xfs_log_force(log->l_mp, seq, _RET_IP_);
1354 xlog_cil_push_now(log, seq, true);
1358 * Conditionally push the CIL based on the sequence passed in.
1360 * We only need to push if we haven't already pushed the sequence number given.
1361 * Hence the only time we will trigger a push here is if the push sequence is
1362 * the same as the current context.
1364 * We return the current commit lsn to allow the callers to determine if a
1365 * iclog flush is necessary following this call.
1372 struct xfs_cil *cil = log->l_cilp;
1373 struct xfs_cil_ctx *ctx;
1374 xfs_lsn_t commit_lsn = NULLCOMMITLSN;
1376 ASSERT(sequence <= cil->xc_current_sequence);
1379 sequence = cil->xc_current_sequence;
1380 trace_xfs_log_force(log->l_mp, sequence, _RET_IP_);
1383 * check to see if we need to force out the current context.
1384 * xlog_cil_push() handles racing pushes for the same sequence,
1385 * so no need to deal with it here.
1388 xlog_cil_push_now(log, sequence, false);
1391 * See if we can find a previous sequence still committing.
1392 * We need to wait for all previous sequence commits to complete
1393 * before allowing the force of push_seq to go ahead. Hence block
1394 * on commits for those as well.
1396 spin_lock(&cil->xc_push_lock);
1397 list_for_each_entry(ctx, &cil->xc_committing, committing) {
1399 * Avoid getting stuck in this loop because we were woken by the
1400 * shutdown, but then went back to sleep once already in the
1403 if (xlog_is_shutdown(log))
1405 if (ctx->sequence > sequence)
1407 if (!ctx->commit_lsn) {
1409 * It is still being pushed! Wait for the push to
1410 * complete, then start again from the beginning.
1412 XFS_STATS_INC(log->l_mp, xs_log_force_sleep);
1413 xlog_wait(&cil->xc_commit_wait, &cil->xc_push_lock);
1416 if (ctx->sequence != sequence)
1419 commit_lsn = ctx->commit_lsn;
1423 * The call to xlog_cil_push_now() executes the push in the background.
1424 * Hence by the time we have got here it our sequence may not have been
1425 * pushed yet. This is true if the current sequence still matches the
1426 * push sequence after the above wait loop and the CIL still contains
1427 * dirty objects. This is guaranteed by the push code first adding the
1428 * context to the committing list before emptying the CIL.
1430 * Hence if we don't find the context in the committing list and the
1431 * current sequence number is unchanged then the CIL contents are
1432 * significant. If the CIL is empty, if means there was nothing to push
1433 * and that means there is nothing to wait for. If the CIL is not empty,
1434 * it means we haven't yet started the push, because if it had started
1435 * we would have found the context on the committing list.
1437 if (sequence == cil->xc_current_sequence &&
1438 !list_empty(&cil->xc_cil)) {
1439 spin_unlock(&cil->xc_push_lock);
1443 spin_unlock(&cil->xc_push_lock);
1447 * We detected a shutdown in progress. We need to trigger the log force
1448 * to pass through it's iclog state machine error handling, even though
1449 * we are already in a shutdown state. Hence we can't return
1450 * NULLCOMMITLSN here as that has special meaning to log forces (i.e.
1451 * LSN is already stable), so we return a zero LSN instead.
1454 spin_unlock(&cil->xc_push_lock);
1459 * Check if the current log item was first committed in this sequence.
1460 * We can't rely on just the log item being in the CIL, we have to check
1461 * the recorded commit sequence number.
1463 * Note: for this to be used in a non-racy manner, it has to be called with
1464 * CIL flushing locked out. As a result, it should only be used during the
1465 * transaction commit process when deciding what to format into the item.
1468 xfs_log_item_in_current_chkpt(
1469 struct xfs_log_item *lip)
1471 struct xfs_cil *cil = lip->li_mountp->m_log->l_cilp;
1473 if (list_empty(&lip->li_cil))
1477 * li_seq is written on the first commit of a log item to record the
1478 * first checkpoint it is written to. Hence if it is different to the
1479 * current sequence, we're in a new checkpoint.
1481 return lip->li_seq == READ_ONCE(cil->xc_current_sequence);
1485 * Perform initial CIL structure initialisation.
1491 struct xfs_cil *cil;
1492 struct xfs_cil_ctx *ctx;
1494 cil = kmem_zalloc(sizeof(*cil), KM_MAYFAIL);
1498 * Limit the CIL pipeline depth to 4 concurrent works to bound the
1499 * concurrency the log spinlocks will be exposed to.
1501 cil->xc_push_wq = alloc_workqueue("xfs-cil/%s",
1502 XFS_WQFLAGS(WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_UNBOUND),
1503 4, log->l_mp->m_super->s_id);
1504 if (!cil->xc_push_wq)
1505 goto out_destroy_cil;
1507 INIT_LIST_HEAD(&cil->xc_cil);
1508 INIT_LIST_HEAD(&cil->xc_committing);
1509 spin_lock_init(&cil->xc_cil_lock);
1510 spin_lock_init(&cil->xc_push_lock);
1511 init_waitqueue_head(&cil->xc_push_wait);
1512 init_rwsem(&cil->xc_ctx_lock);
1513 init_waitqueue_head(&cil->xc_start_wait);
1514 init_waitqueue_head(&cil->xc_commit_wait);
1518 ctx = xlog_cil_ctx_alloc();
1519 xlog_cil_ctx_switch(cil, ctx);
1532 if (log->l_cilp->xc_ctx) {
1533 if (log->l_cilp->xc_ctx->ticket)
1534 xfs_log_ticket_put(log->l_cilp->xc_ctx->ticket);
1535 kmem_free(log->l_cilp->xc_ctx);
1538 ASSERT(list_empty(&log->l_cilp->xc_cil));
1539 destroy_workqueue(log->l_cilp->xc_push_wq);
1540 kmem_free(log->l_cilp);