xref: /linux/fs/xfs/xfs_log_cil.c (revision e78f70bad29c5ae1e1076698b690b15794e9b81e)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2010 Red Hat, Inc. All Rights Reserved.
4  */
5 
6 #include "xfs.h"
7 #include "xfs_fs.h"
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"
16 #include "xfs_log.h"
17 #include "xfs_log_priv.h"
18 #include "xfs_trace.h"
19 #include "xfs_discard.h"
20 
21 /*
22  * Allocate a new ticket. Failing to get a new ticket makes it really hard to
23  * recover, so we don't allow failure here. Also, we allocate in a context that
24  * we don't want to be issuing transactions from, so we need to tell the
25  * allocation code this as well.
26  *
27  * We don't reserve any space for the ticket - we are going to steal whatever
28  * space we require from transactions as they commit. To ensure we reserve all
29  * the space required, we need to set the current reservation of the ticket to
30  * zero so that we know to steal the initial transaction overhead from the
31  * first transaction commit.
32  */
33 static struct xlog_ticket *
34 xlog_cil_ticket_alloc(
35 	struct xlog	*log)
36 {
37 	struct xlog_ticket *tic;
38 
39 	tic = xlog_ticket_alloc(log, 0, 1, 0);
40 
41 	/*
42 	 * set the current reservation to zero so we know to steal the basic
43 	 * transaction overhead reservation from the first transaction commit.
44 	 */
45 	tic->t_curr_res = 0;
46 	tic->t_iclog_hdrs = 0;
47 	return tic;
48 }
49 
50 static inline void
51 xlog_cil_set_iclog_hdr_count(struct xfs_cil *cil)
52 {
53 	struct xlog	*log = cil->xc_log;
54 
55 	atomic_set(&cil->xc_iclog_hdrs,
56 		   (XLOG_CIL_BLOCKING_SPACE_LIMIT(log) /
57 			(log->l_iclog_size - log->l_iclog_hsize)));
58 }
59 
60 /*
61  * Check if the current log item was first committed in this sequence.
62  * We can't rely on just the log item being in the CIL, we have to check
63  * the recorded commit sequence number.
64  *
65  * Note: for this to be used in a non-racy manner, it has to be called with
66  * CIL flushing locked out. As a result, it should only be used during the
67  * transaction commit process when deciding what to format into the item.
68  */
69 static bool
70 xlog_item_in_current_chkpt(
71 	struct xfs_cil		*cil,
72 	struct xfs_log_item	*lip)
73 {
74 	if (test_bit(XLOG_CIL_EMPTY, &cil->xc_flags))
75 		return false;
76 
77 	/*
78 	 * li_seq is written on the first commit of a log item to record the
79 	 * first checkpoint it is written to. Hence if it is different to the
80 	 * current sequence, we're in a new checkpoint.
81 	 */
82 	return lip->li_seq == READ_ONCE(cil->xc_current_sequence);
83 }
84 
85 bool
86 xfs_log_item_in_current_chkpt(
87 	struct xfs_log_item *lip)
88 {
89 	return xlog_item_in_current_chkpt(lip->li_log->l_cilp, lip);
90 }
91 
92 /*
93  * Unavoidable forward declaration - xlog_cil_push_work() calls
94  * xlog_cil_ctx_alloc() itself.
95  */
96 static void xlog_cil_push_work(struct work_struct *work);
97 
98 static struct xfs_cil_ctx *
99 xlog_cil_ctx_alloc(void)
100 {
101 	struct xfs_cil_ctx	*ctx;
102 
103 	ctx = kzalloc(sizeof(*ctx), GFP_KERNEL | __GFP_NOFAIL);
104 	INIT_LIST_HEAD(&ctx->committing);
105 	INIT_LIST_HEAD(&ctx->busy_extents.extent_list);
106 	INIT_LIST_HEAD(&ctx->log_items);
107 	INIT_LIST_HEAD(&ctx->lv_chain);
108 	INIT_WORK(&ctx->push_work, xlog_cil_push_work);
109 	return ctx;
110 }
111 
112 /*
113  * Aggregate the CIL per cpu structures into global counts, lists, etc and
114  * clear the percpu state ready for the next context to use. This is called
115  * from the push code with the context lock held exclusively, hence nothing else
116  * will be accessing or modifying the per-cpu counters.
117  */
118 static void
119 xlog_cil_push_pcp_aggregate(
120 	struct xfs_cil		*cil,
121 	struct xfs_cil_ctx	*ctx)
122 {
123 	struct xlog_cil_pcp	*cilpcp;
124 	int			cpu;
125 
126 	for_each_cpu(cpu, &ctx->cil_pcpmask) {
127 		cilpcp = per_cpu_ptr(cil->xc_pcp, cpu);
128 
129 		ctx->ticket->t_curr_res += cilpcp->space_reserved;
130 		cilpcp->space_reserved = 0;
131 
132 		if (!list_empty(&cilpcp->busy_extents)) {
133 			list_splice_init(&cilpcp->busy_extents,
134 					&ctx->busy_extents.extent_list);
135 		}
136 		if (!list_empty(&cilpcp->log_items))
137 			list_splice_init(&cilpcp->log_items, &ctx->log_items);
138 
139 		/*
140 		 * We're in the middle of switching cil contexts.  Reset the
141 		 * counter we use to detect when the current context is nearing
142 		 * full.
143 		 */
144 		cilpcp->space_used = 0;
145 	}
146 }
147 
148 /*
149  * Aggregate the CIL per-cpu space used counters into the global atomic value.
150  * This is called when the per-cpu counter aggregation will first pass the soft
151  * limit threshold so we can switch to atomic counter aggregation for accurate
152  * detection of hard limit traversal.
153  */
154 static void
155 xlog_cil_insert_pcp_aggregate(
156 	struct xfs_cil		*cil,
157 	struct xfs_cil_ctx	*ctx)
158 {
159 	int			cpu;
160 	int			count = 0;
161 
162 	/* Trigger atomic updates then aggregate only for the first caller */
163 	if (!test_and_clear_bit(XLOG_CIL_PCP_SPACE, &cil->xc_flags))
164 		return;
165 
166 	/*
167 	 * We can race with other cpus setting cil_pcpmask.  However, we've
168 	 * atomically cleared PCP_SPACE which forces other threads to add to
169 	 * the global space used count.  cil_pcpmask is a superset of cilpcp
170 	 * structures that could have a nonzero space_used.
171 	 */
172 	for_each_cpu(cpu, &ctx->cil_pcpmask) {
173 		struct xlog_cil_pcp	*cilpcp = per_cpu_ptr(cil->xc_pcp, cpu);
174 
175 		count += xchg(&cilpcp->space_used, 0);
176 	}
177 	atomic_add(count, &ctx->space_used);
178 }
179 
180 static void
181 xlog_cil_ctx_switch(
182 	struct xfs_cil		*cil,
183 	struct xfs_cil_ctx	*ctx)
184 {
185 	xlog_cil_set_iclog_hdr_count(cil);
186 	set_bit(XLOG_CIL_EMPTY, &cil->xc_flags);
187 	set_bit(XLOG_CIL_PCP_SPACE, &cil->xc_flags);
188 	ctx->sequence = ++cil->xc_current_sequence;
189 	ctx->cil = cil;
190 	cil->xc_ctx = ctx;
191 }
192 
193 /*
194  * After the first stage of log recovery is done, we know where the head and
195  * tail of the log are. We need this log initialisation done before we can
196  * initialise the first CIL checkpoint context.
197  *
198  * Here we allocate a log ticket to track space usage during a CIL push.  This
199  * ticket is passed to xlog_write() directly so that we don't slowly leak log
200  * space by failing to account for space used by log headers and additional
201  * region headers for split regions.
202  */
203 void
204 xlog_cil_init_post_recovery(
205 	struct xlog	*log)
206 {
207 	log->l_cilp->xc_ctx->ticket = xlog_cil_ticket_alloc(log);
208 	log->l_cilp->xc_ctx->sequence = 1;
209 	xlog_cil_set_iclog_hdr_count(log->l_cilp);
210 }
211 
212 static inline int
213 xlog_cil_iovec_space(
214 	uint	niovecs)
215 {
216 	return round_up((sizeof(struct xfs_log_vec) +
217 					niovecs * sizeof(struct xfs_log_iovec)),
218 			sizeof(uint64_t));
219 }
220 
221 /*
222  * Allocate or pin log vector buffers for CIL insertion.
223  *
224  * The CIL currently uses disposable buffers for copying a snapshot of the
225  * modified items into the log during a push. The biggest problem with this is
226  * the requirement to allocate the disposable buffer during the commit if:
227  *	a) does not exist; or
228  *	b) it is too small
229  *
230  * If we do this allocation within xlog_cil_insert_format_items(), it is done
231  * under the xc_ctx_lock, which means that a CIL push cannot occur during
232  * the memory allocation. This means that we have a potential deadlock situation
233  * under low memory conditions when we have lots of dirty metadata pinned in
234  * the CIL and we need a CIL commit to occur to free memory.
235  *
236  * To avoid this, we need to move the memory allocation outside the
237  * xc_ctx_lock, but because the log vector buffers are disposable, that opens
238  * up a TOCTOU race condition w.r.t. the CIL committing and removing the log
239  * vector buffers between the check and the formatting of the item into the
240  * log vector buffer within the xc_ctx_lock.
241  *
242  * Because the log vector buffer needs to be unchanged during the CIL push
243  * process, we cannot share the buffer between the transaction commit (which
244  * modifies the buffer) and the CIL push context that is writing the changes
245  * into the log. This means skipping preallocation of buffer space is
246  * unreliable, but we most definitely do not want to be allocating and freeing
247  * buffers unnecessarily during commits when overwrites can be done safely.
248  *
249  * The simplest solution to this problem is to allocate a shadow buffer when a
250  * log item is committed for the second time, and then to only use this buffer
251  * if necessary. The buffer can remain attached to the log item until such time
252  * it is needed, and this is the buffer that is reallocated to match the size of
253  * the incoming modification. Then during the formatting of the item we can swap
254  * the active buffer with the new one if we can't reuse the existing buffer. We
255  * don't free the old buffer as it may be reused on the next modification if
256  * it's size is right, otherwise we'll free and reallocate it at that point.
257  *
258  * This function builds a vector for the changes in each log item in the
259  * transaction. It then works out the length of the buffer needed for each log
260  * item, allocates them and attaches the vector to the log item in preparation
261  * for the formatting step which occurs under the xc_ctx_lock.
262  *
263  * While this means the memory footprint goes up, it avoids the repeated
264  * alloc/free pattern that repeated modifications of an item would otherwise
265  * cause, and hence minimises the CPU overhead of such behaviour.
266  */
267 static void
268 xlog_cil_alloc_shadow_bufs(
269 	struct xlog		*log,
270 	struct xfs_trans	*tp)
271 {
272 	struct xfs_log_item	*lip;
273 
274 	list_for_each_entry(lip, &tp->t_items, li_trans) {
275 		struct xfs_log_vec *lv;
276 		int	niovecs = 0;
277 		int	nbytes = 0;
278 		int	buf_size;
279 		bool	ordered = false;
280 
281 		/* Skip items which aren't dirty in this transaction. */
282 		if (!test_bit(XFS_LI_DIRTY, &lip->li_flags))
283 			continue;
284 
285 		/* get number of vecs and size of data to be stored */
286 		lip->li_ops->iop_size(lip, &niovecs, &nbytes);
287 
288 		/*
289 		 * Ordered items need to be tracked but we do not wish to write
290 		 * them. We need a logvec to track the object, but we do not
291 		 * need an iovec or buffer to be allocated for copying data.
292 		 */
293 		if (niovecs == XFS_LOG_VEC_ORDERED) {
294 			ordered = true;
295 			niovecs = 0;
296 			nbytes = 0;
297 		}
298 
299 		/*
300 		 * We 64-bit align the length of each iovec so that the start of
301 		 * the next one is naturally aligned.  We'll need to account for
302 		 * that slack space here.
303 		 *
304 		 * We also add the xlog_op_header to each region when
305 		 * formatting, but that's not accounted to the size of the item
306 		 * at this point. Hence we'll need an addition number of bytes
307 		 * for each vector to hold an opheader.
308 		 *
309 		 * Then round nbytes up to 64-bit alignment so that the initial
310 		 * buffer alignment is easy to calculate and verify.
311 		 */
312 		nbytes = xlog_item_space(niovecs, nbytes);
313 
314 		/*
315 		 * The data buffer needs to start 64-bit aligned, so round up
316 		 * that space to ensure we can align it appropriately and not
317 		 * overrun the buffer.
318 		 */
319 		buf_size = nbytes + xlog_cil_iovec_space(niovecs);
320 
321 		/*
322 		 * if we have no shadow buffer, or it is too small, we need to
323 		 * reallocate it.
324 		 */
325 		if (!lip->li_lv_shadow ||
326 		    buf_size > lip->li_lv_shadow->lv_size) {
327 			/*
328 			 * We free and allocate here as a realloc would copy
329 			 * unnecessary data. We don't use kvzalloc() for the
330 			 * same reason - we don't need to zero the data area in
331 			 * the buffer, only the log vector header and the iovec
332 			 * storage.
333 			 */
334 			kvfree(lip->li_lv_shadow);
335 			lv = xlog_kvmalloc(buf_size);
336 
337 			memset(lv, 0, xlog_cil_iovec_space(niovecs));
338 
339 			INIT_LIST_HEAD(&lv->lv_list);
340 			lv->lv_item = lip;
341 			lv->lv_size = buf_size;
342 			if (ordered)
343 				lv->lv_buf_len = XFS_LOG_VEC_ORDERED;
344 			else
345 				lv->lv_iovecp = (struct xfs_log_iovec *)&lv[1];
346 			lip->li_lv_shadow = lv;
347 		} else {
348 			/* same or smaller, optimise common overwrite case */
349 			lv = lip->li_lv_shadow;
350 			if (ordered)
351 				lv->lv_buf_len = XFS_LOG_VEC_ORDERED;
352 			else
353 				lv->lv_buf_len = 0;
354 			lv->lv_bytes = 0;
355 		}
356 
357 		/* Ensure the lv is set up according to ->iop_size */
358 		lv->lv_niovecs = niovecs;
359 
360 		/* The allocated data region lies beyond the iovec region */
361 		lv->lv_buf = (char *)lv + xlog_cil_iovec_space(niovecs);
362 	}
363 
364 }
365 
366 /*
367  * Prepare the log item for insertion into the CIL. Calculate the difference in
368  * log space it will consume, and if it is a new item pin it as well.
369  */
370 STATIC void
371 xfs_cil_prepare_item(
372 	struct xlog		*log,
373 	struct xfs_log_vec	*lv,
374 	struct xfs_log_vec	*old_lv,
375 	int			*diff_len)
376 {
377 	/* Account for the new LV being passed in */
378 	if (lv->lv_buf_len != XFS_LOG_VEC_ORDERED)
379 		*diff_len += lv->lv_bytes;
380 
381 	/*
382 	 * If there is no old LV, this is the first time we've seen the item in
383 	 * this CIL context and so we need to pin it. If we are replacing the
384 	 * old_lv, then remove the space it accounts for and make it the shadow
385 	 * buffer for later freeing. In both cases we are now switching to the
386 	 * shadow buffer, so update the pointer to it appropriately.
387 	 */
388 	if (!old_lv) {
389 		if (lv->lv_item->li_ops->iop_pin)
390 			lv->lv_item->li_ops->iop_pin(lv->lv_item);
391 		lv->lv_item->li_lv_shadow = NULL;
392 	} else if (old_lv != lv) {
393 		ASSERT(lv->lv_buf_len != XFS_LOG_VEC_ORDERED);
394 
395 		*diff_len -= old_lv->lv_bytes;
396 		lv->lv_item->li_lv_shadow = old_lv;
397 	}
398 
399 	/* attach new log vector to log item */
400 	lv->lv_item->li_lv = lv;
401 
402 	/*
403 	 * If this is the first time the item is being committed to the
404 	 * CIL, store the sequence number on the log item so we can
405 	 * tell in future commits whether this is the first checkpoint
406 	 * the item is being committed into.
407 	 */
408 	if (!lv->lv_item->li_seq)
409 		lv->lv_item->li_seq = log->l_cilp->xc_ctx->sequence;
410 }
411 
412 /*
413  * Format log item into a flat buffers
414  *
415  * For delayed logging, we need to hold a formatted buffer containing all the
416  * changes on the log item. This enables us to relog the item in memory and
417  * write it out asynchronously without needing to relock the object that was
418  * modified at the time it gets written into the iclog.
419  *
420  * This function takes the prepared log vectors attached to each log item, and
421  * formats the changes into the log vector buffer. The buffer it uses is
422  * dependent on the current state of the vector in the CIL - the shadow lv is
423  * guaranteed to be large enough for the current modification, but we will only
424  * use that if we can't reuse the existing lv. If we can't reuse the existing
425  * lv, then simple swap it out for the shadow lv. We don't free it - that is
426  * done lazily either by th enext modification or the freeing of the log item.
427  *
428  * We don't set up region headers during this process; we simply copy the
429  * regions into the flat buffer. We can do this because we still have to do a
430  * formatting step to write the regions into the iclog buffer.  Writing the
431  * ophdrs during the iclog write means that we can support splitting large
432  * regions across iclog boundares without needing a change in the format of the
433  * item/region encapsulation.
434  *
435  * Hence what we need to do now is change the rewrite the vector array to point
436  * to the copied region inside the buffer we just allocated. This allows us to
437  * format the regions into the iclog as though they are being formatted
438  * directly out of the objects themselves.
439  */
440 static void
441 xlog_cil_insert_format_items(
442 	struct xlog		*log,
443 	struct xfs_trans	*tp,
444 	int			*diff_len)
445 {
446 	struct xfs_log_item	*lip;
447 
448 	/* Bail out if we didn't find a log item.  */
449 	if (list_empty(&tp->t_items)) {
450 		ASSERT(0);
451 		return;
452 	}
453 
454 	list_for_each_entry(lip, &tp->t_items, li_trans) {
455 		struct xfs_log_vec *lv;
456 		struct xfs_log_vec *old_lv = NULL;
457 		struct xfs_log_vec *shadow;
458 		bool	ordered = false;
459 
460 		/* Skip items which aren't dirty in this transaction. */
461 		if (!test_bit(XFS_LI_DIRTY, &lip->li_flags))
462 			continue;
463 
464 		/*
465 		 * The formatting size information is already attached to
466 		 * the shadow lv on the log item.
467 		 */
468 		shadow = lip->li_lv_shadow;
469 		if (shadow->lv_buf_len == XFS_LOG_VEC_ORDERED)
470 			ordered = true;
471 
472 		/* Skip items that do not have any vectors for writing */
473 		if (!shadow->lv_niovecs && !ordered)
474 			continue;
475 
476 		/* compare to existing item size */
477 		old_lv = lip->li_lv;
478 		if (lip->li_lv && shadow->lv_size <= lip->li_lv->lv_size) {
479 			/* same or smaller, optimise common overwrite case */
480 			lv = lip->li_lv;
481 
482 			if (ordered)
483 				goto insert;
484 
485 			/*
486 			 * set the item up as though it is a new insertion so
487 			 * that the space reservation accounting is correct.
488 			 */
489 			*diff_len -= lv->lv_bytes;
490 
491 			/* Ensure the lv is set up according to ->iop_size */
492 			lv->lv_niovecs = shadow->lv_niovecs;
493 
494 			/* reset the lv buffer information for new formatting */
495 			lv->lv_buf_len = 0;
496 			lv->lv_bytes = 0;
497 			lv->lv_buf = (char *)lv +
498 					xlog_cil_iovec_space(lv->lv_niovecs);
499 		} else {
500 			/* switch to shadow buffer! */
501 			lv = shadow;
502 			lv->lv_item = lip;
503 			if (ordered) {
504 				/* track as an ordered logvec */
505 				ASSERT(lip->li_lv == NULL);
506 				goto insert;
507 			}
508 		}
509 
510 		ASSERT(IS_ALIGNED((unsigned long)lv->lv_buf, sizeof(uint64_t)));
511 		lip->li_ops->iop_format(lip, lv);
512 insert:
513 		xfs_cil_prepare_item(log, lv, old_lv, diff_len);
514 	}
515 }
516 
517 /*
518  * The use of lockless waitqueue_active() requires that the caller has
519  * serialised itself against the wakeup call in xlog_cil_push_work(). That
520  * can be done by either holding the push lock or the context lock.
521  */
522 static inline bool
523 xlog_cil_over_hard_limit(
524 	struct xlog	*log,
525 	int32_t		space_used)
526 {
527 	if (waitqueue_active(&log->l_cilp->xc_push_wait))
528 		return true;
529 	if (space_used >= XLOG_CIL_BLOCKING_SPACE_LIMIT(log))
530 		return true;
531 	return false;
532 }
533 
534 /*
535  * Insert the log items into the CIL and calculate the difference in space
536  * consumed by the item. Add the space to the checkpoint ticket and calculate
537  * if the change requires additional log metadata. If it does, take that space
538  * as well. Remove the amount of space we added to the checkpoint ticket from
539  * the current transaction ticket so that the accounting works out correctly.
540  */
541 static void
542 xlog_cil_insert_items(
543 	struct xlog		*log,
544 	struct xfs_trans	*tp,
545 	uint32_t		released_space)
546 {
547 	struct xfs_cil		*cil = log->l_cilp;
548 	struct xfs_cil_ctx	*ctx = cil->xc_ctx;
549 	struct xfs_log_item	*lip;
550 	int			len = 0;
551 	int			iovhdr_res = 0, split_res = 0, ctx_res = 0;
552 	int			space_used;
553 	int			order;
554 	unsigned int		cpu_nr;
555 	struct xlog_cil_pcp	*cilpcp;
556 
557 	ASSERT(tp);
558 
559 	/*
560 	 * We can do this safely because the context can't checkpoint until we
561 	 * are done so it doesn't matter exactly how we update the CIL.
562 	 */
563 	xlog_cil_insert_format_items(log, tp, &len);
564 
565 	/*
566 	 * Subtract the space released by intent cancelation from the space we
567 	 * consumed so that we remove it from the CIL space and add it back to
568 	 * the current transaction reservation context.
569 	 */
570 	len -= released_space;
571 
572 	/*
573 	 * Grab the per-cpu pointer for the CIL before we start any accounting.
574 	 * That ensures that we are running with pre-emption disabled and so we
575 	 * can't be scheduled away between split sample/update operations that
576 	 * are done without outside locking to serialise them.
577 	 */
578 	cpu_nr = get_cpu();
579 	cilpcp = this_cpu_ptr(cil->xc_pcp);
580 
581 	/* Tell the future push that there was work added by this CPU. */
582 	if (!cpumask_test_cpu(cpu_nr, &ctx->cil_pcpmask))
583 		cpumask_test_and_set_cpu(cpu_nr, &ctx->cil_pcpmask);
584 
585 	/*
586 	 * We need to take the CIL checkpoint unit reservation on the first
587 	 * commit into the CIL. Test the XLOG_CIL_EMPTY bit first so we don't
588 	 * unnecessarily do an atomic op in the fast path here. We can clear the
589 	 * XLOG_CIL_EMPTY bit as we are under the xc_ctx_lock here and that
590 	 * needs to be held exclusively to reset the XLOG_CIL_EMPTY bit.
591 	 */
592 	if (test_bit(XLOG_CIL_EMPTY, &cil->xc_flags) &&
593 	    test_and_clear_bit(XLOG_CIL_EMPTY, &cil->xc_flags))
594 		ctx_res = ctx->ticket->t_unit_res;
595 
596 	/*
597 	 * Check if we need to steal iclog headers. atomic_read() is not a
598 	 * locked atomic operation, so we can check the value before we do any
599 	 * real atomic ops in the fast path. If we've already taken the CIL unit
600 	 * reservation from this commit, we've already got one iclog header
601 	 * space reserved so we have to account for that otherwise we risk
602 	 * overrunning the reservation on this ticket.
603 	 *
604 	 * If the CIL is already at the hard limit, we might need more header
605 	 * space that originally reserved. So steal more header space from every
606 	 * commit that occurs once we are over the hard limit to ensure the CIL
607 	 * push won't run out of reservation space.
608 	 *
609 	 * This can steal more than we need, but that's OK.
610 	 *
611 	 * The cil->xc_ctx_lock provides the serialisation necessary for safely
612 	 * calling xlog_cil_over_hard_limit() in this context.
613 	 */
614 	space_used = atomic_read(&ctx->space_used) + cilpcp->space_used + len;
615 	if (atomic_read(&cil->xc_iclog_hdrs) > 0 ||
616 	    xlog_cil_over_hard_limit(log, space_used)) {
617 		split_res = log->l_iclog_hsize +
618 					sizeof(struct xlog_op_header);
619 		if (ctx_res)
620 			ctx_res += split_res * (tp->t_ticket->t_iclog_hdrs - 1);
621 		else
622 			ctx_res = split_res * tp->t_ticket->t_iclog_hdrs;
623 		atomic_sub(tp->t_ticket->t_iclog_hdrs, &cil->xc_iclog_hdrs);
624 	}
625 	cilpcp->space_reserved += ctx_res;
626 
627 	/*
628 	 * Accurately account when over the soft limit, otherwise fold the
629 	 * percpu count into the global count if over the per-cpu threshold.
630 	 */
631 	if (!test_bit(XLOG_CIL_PCP_SPACE, &cil->xc_flags)) {
632 		atomic_add(len, &ctx->space_used);
633 	} else if (cilpcp->space_used + len >
634 			(XLOG_CIL_SPACE_LIMIT(log) / num_online_cpus())) {
635 		space_used = atomic_add_return(cilpcp->space_used + len,
636 						&ctx->space_used);
637 		cilpcp->space_used = 0;
638 
639 		/*
640 		 * If we just transitioned over the soft limit, we need to
641 		 * transition to the global atomic counter.
642 		 */
643 		if (space_used >= XLOG_CIL_SPACE_LIMIT(log))
644 			xlog_cil_insert_pcp_aggregate(cil, ctx);
645 	} else {
646 		cilpcp->space_used += len;
647 	}
648 	/* attach the transaction to the CIL if it has any busy extents */
649 	if (!list_empty(&tp->t_busy))
650 		list_splice_init(&tp->t_busy, &cilpcp->busy_extents);
651 
652 	/*
653 	 * Now update the order of everything modified in the transaction
654 	 * and insert items into the CIL if they aren't already there.
655 	 * We do this here so we only need to take the CIL lock once during
656 	 * the transaction commit.
657 	 */
658 	order = atomic_inc_return(&ctx->order_id);
659 	list_for_each_entry(lip, &tp->t_items, li_trans) {
660 		/* Skip items which aren't dirty in this transaction. */
661 		if (!test_bit(XFS_LI_DIRTY, &lip->li_flags))
662 			continue;
663 
664 		lip->li_order_id = order;
665 		if (!list_empty(&lip->li_cil))
666 			continue;
667 		list_add_tail(&lip->li_cil, &cilpcp->log_items);
668 	}
669 	put_cpu();
670 
671 	/*
672 	 * If we've overrun the reservation, dump the tx details before we move
673 	 * the log items. Shutdown is imminent...
674 	 */
675 	tp->t_ticket->t_curr_res -= ctx_res + len;
676 	if (WARN_ON(tp->t_ticket->t_curr_res < 0)) {
677 		xfs_warn(log->l_mp, "Transaction log reservation overrun:");
678 		xfs_warn(log->l_mp,
679 			 "  log items: %d bytes (iov hdrs: %d bytes)",
680 			 len, iovhdr_res);
681 		xfs_warn(log->l_mp, "  split region headers: %d bytes",
682 			 split_res);
683 		xfs_warn(log->l_mp, "  ctx ticket: %d bytes", ctx_res);
684 		xlog_print_trans(tp);
685 		xlog_force_shutdown(log, SHUTDOWN_LOG_IO_ERROR);
686 	}
687 }
688 
689 static inline void
690 xlog_cil_ail_insert_batch(
691 	struct xfs_ail		*ailp,
692 	struct xfs_ail_cursor	*cur,
693 	struct xfs_log_item	**log_items,
694 	int			nr_items,
695 	xfs_lsn_t		commit_lsn)
696 {
697 	int	i;
698 
699 	spin_lock(&ailp->ail_lock);
700 	/* xfs_trans_ail_update_bulk drops ailp->ail_lock */
701 	xfs_trans_ail_update_bulk(ailp, cur, log_items, nr_items, commit_lsn);
702 
703 	for (i = 0; i < nr_items; i++) {
704 		struct xfs_log_item *lip = log_items[i];
705 
706 		if (lip->li_ops->iop_unpin)
707 			lip->li_ops->iop_unpin(lip, 0);
708 	}
709 }
710 
711 /*
712  * Take the checkpoint's log vector chain of items and insert the attached log
713  * items into the AIL. This uses bulk insertion techniques to minimise AIL lock
714  * traffic.
715  *
716  * The AIL tracks log items via the start record LSN of the checkpoint,
717  * not the commit record LSN. This is because we can pipeline multiple
718  * checkpoints, and so the start record of checkpoint N+1 can be
719  * written before the commit record of checkpoint N. i.e:
720  *
721  *   start N			commit N
722  *	+-------------+------------+----------------+
723  *		  start N+1			commit N+1
724  *
725  * The tail of the log cannot be moved to the LSN of commit N when all
726  * the items of that checkpoint are written back, because then the
727  * start record for N+1 is no longer in the active portion of the log
728  * and recovery will fail/corrupt the filesystem.
729  *
730  * Hence when all the log items in checkpoint N are written back, the
731  * tail of the log most now only move as far forwards as the start LSN
732  * of checkpoint N+1.
733  *
734  * If we are called with the aborted flag set, it is because a log write during
735  * a CIL checkpoint commit has failed. In this case, all the items in the
736  * checkpoint have already gone through iop_committed and iop_committing, which
737  * means that checkpoint commit abort handling is treated exactly the same as an
738  * iclog write error even though we haven't started any IO yet. Hence in this
739  * case all we need to do is iop_committed processing, followed by an
740  * iop_unpin(aborted) call.
741  *
742  * The AIL cursor is used to optimise the insert process. If commit_lsn is not
743  * at the end of the AIL, the insert cursor avoids the need to walk the AIL to
744  * find the insertion point on every xfs_log_item_batch_insert() call. This
745  * saves a lot of needless list walking and is a net win, even though it
746  * slightly increases that amount of AIL lock traffic to set it up and tear it
747  * down.
748  */
749 static void
750 xlog_cil_ail_insert(
751 	struct xfs_cil_ctx	*ctx,
752 	bool			aborted)
753 {
754 #define LOG_ITEM_BATCH_SIZE	32
755 	struct xfs_ail		*ailp = ctx->cil->xc_log->l_ailp;
756 	struct xfs_log_item	*log_items[LOG_ITEM_BATCH_SIZE];
757 	struct xfs_log_vec	*lv;
758 	struct xfs_ail_cursor	cur;
759 	xfs_lsn_t		old_head;
760 	int			i = 0;
761 
762 	/*
763 	 * Update the AIL head LSN with the commit record LSN of this
764 	 * checkpoint. As iclogs are always completed in order, this should
765 	 * always be the same (as iclogs can contain multiple commit records) or
766 	 * higher LSN than the current head. We do this before insertion of the
767 	 * items so that log space checks during insertion will reflect the
768 	 * space that this checkpoint has already consumed.  We call
769 	 * xfs_ail_update_finish() so that tail space and space-based wakeups
770 	 * will be recalculated appropriately.
771 	 */
772 	ASSERT(XFS_LSN_CMP(ctx->commit_lsn, ailp->ail_head_lsn) >= 0 ||
773 			aborted);
774 	spin_lock(&ailp->ail_lock);
775 	xfs_trans_ail_cursor_last(ailp, &cur, ctx->start_lsn);
776 	old_head = ailp->ail_head_lsn;
777 	ailp->ail_head_lsn = ctx->commit_lsn;
778 	/* xfs_ail_update_finish() drops the ail_lock */
779 	xfs_ail_update_finish(ailp, NULLCOMMITLSN);
780 
781 	/*
782 	 * We move the AIL head forwards to account for the space used in the
783 	 * log before we remove that space from the grant heads. This prevents a
784 	 * transient condition where reservation space appears to become
785 	 * available on return, only for it to disappear again immediately as
786 	 * the AIL head update accounts in the log tail space.
787 	 */
788 	smp_wmb();	/* paired with smp_rmb in xlog_grant_space_left */
789 	xlog_grant_return_space(ailp->ail_log, old_head, ailp->ail_head_lsn);
790 
791 	/* unpin all the log items */
792 	list_for_each_entry(lv, &ctx->lv_chain, lv_list) {
793 		struct xfs_log_item	*lip = lv->lv_item;
794 		xfs_lsn_t		item_lsn;
795 
796 		if (aborted)
797 			set_bit(XFS_LI_ABORTED, &lip->li_flags);
798 
799 		if (lip->li_ops->flags & XFS_ITEM_RELEASE_WHEN_COMMITTED) {
800 			lip->li_ops->iop_release(lip);
801 			continue;
802 		}
803 
804 		if (lip->li_ops->iop_committed)
805 			item_lsn = lip->li_ops->iop_committed(lip,
806 					ctx->start_lsn);
807 		else
808 			item_lsn = ctx->start_lsn;
809 
810 		/* item_lsn of -1 means the item needs no further processing */
811 		if (XFS_LSN_CMP(item_lsn, (xfs_lsn_t)-1) == 0)
812 			continue;
813 
814 		/*
815 		 * if we are aborting the operation, no point in inserting the
816 		 * object into the AIL as we are in a shutdown situation.
817 		 */
818 		if (aborted) {
819 			ASSERT(xlog_is_shutdown(ailp->ail_log));
820 			if (lip->li_ops->iop_unpin)
821 				lip->li_ops->iop_unpin(lip, 1);
822 			continue;
823 		}
824 
825 		if (item_lsn != ctx->start_lsn) {
826 
827 			/*
828 			 * Not a bulk update option due to unusual item_lsn.
829 			 * Push into AIL immediately, rechecking the lsn once
830 			 * we have the ail lock. Then unpin the item. This does
831 			 * not affect the AIL cursor the bulk insert path is
832 			 * using.
833 			 */
834 			spin_lock(&ailp->ail_lock);
835 			if (XFS_LSN_CMP(item_lsn, lip->li_lsn) > 0)
836 				xfs_trans_ail_update(ailp, lip, item_lsn);
837 			else
838 				spin_unlock(&ailp->ail_lock);
839 			if (lip->li_ops->iop_unpin)
840 				lip->li_ops->iop_unpin(lip, 0);
841 			continue;
842 		}
843 
844 		/* Item is a candidate for bulk AIL insert.  */
845 		log_items[i++] = lv->lv_item;
846 		if (i >= LOG_ITEM_BATCH_SIZE) {
847 			xlog_cil_ail_insert_batch(ailp, &cur, log_items,
848 					LOG_ITEM_BATCH_SIZE, ctx->start_lsn);
849 			i = 0;
850 		}
851 	}
852 
853 	/* make sure we insert the remainder! */
854 	if (i)
855 		xlog_cil_ail_insert_batch(ailp, &cur, log_items, i,
856 				ctx->start_lsn);
857 
858 	spin_lock(&ailp->ail_lock);
859 	xfs_trans_ail_cursor_done(&cur);
860 	spin_unlock(&ailp->ail_lock);
861 }
862 
863 static void
864 xlog_cil_free_logvec(
865 	struct list_head	*lv_chain)
866 {
867 	struct xfs_log_vec	*lv;
868 
869 	while (!list_empty(lv_chain)) {
870 		lv = list_first_entry(lv_chain, struct xfs_log_vec, lv_list);
871 		list_del_init(&lv->lv_list);
872 		kvfree(lv);
873 	}
874 }
875 
876 /*
877  * Mark all items committed and clear busy extents. We free the log vector
878  * chains in a separate pass so that we unpin the log items as quickly as
879  * possible.
880  */
881 static void
882 xlog_cil_committed(
883 	struct xfs_cil_ctx	*ctx)
884 {
885 	struct xfs_mount	*mp = ctx->cil->xc_log->l_mp;
886 	bool			abort = xlog_is_shutdown(ctx->cil->xc_log);
887 
888 	/*
889 	 * If the I/O failed, we're aborting the commit and already shutdown.
890 	 * Wake any commit waiters before aborting the log items so we don't
891 	 * block async log pushers on callbacks. Async log pushers explicitly do
892 	 * not wait on log force completion because they may be holding locks
893 	 * required to unpin items.
894 	 */
895 	if (abort) {
896 		spin_lock(&ctx->cil->xc_push_lock);
897 		wake_up_all(&ctx->cil->xc_start_wait);
898 		wake_up_all(&ctx->cil->xc_commit_wait);
899 		spin_unlock(&ctx->cil->xc_push_lock);
900 	}
901 
902 	xlog_cil_ail_insert(ctx, abort);
903 
904 	xfs_extent_busy_sort(&ctx->busy_extents.extent_list);
905 	xfs_extent_busy_clear(&ctx->busy_extents.extent_list,
906 			      xfs_has_discard(mp) && !abort);
907 
908 	spin_lock(&ctx->cil->xc_push_lock);
909 	list_del(&ctx->committing);
910 	spin_unlock(&ctx->cil->xc_push_lock);
911 
912 	xlog_cil_free_logvec(&ctx->lv_chain);
913 
914 	if (!list_empty(&ctx->busy_extents.extent_list)) {
915 		ctx->busy_extents.owner = ctx;
916 		xfs_discard_extents(mp, &ctx->busy_extents);
917 		return;
918 	}
919 
920 	kfree(ctx);
921 }
922 
923 void
924 xlog_cil_process_committed(
925 	struct list_head	*list)
926 {
927 	struct xfs_cil_ctx	*ctx;
928 
929 	while ((ctx = list_first_entry_or_null(list,
930 			struct xfs_cil_ctx, iclog_entry))) {
931 		list_del(&ctx->iclog_entry);
932 		xlog_cil_committed(ctx);
933 	}
934 }
935 
936 /*
937 * Record the LSN of the iclog we were just granted space to start writing into.
938 * If the context doesn't have a start_lsn recorded, then this iclog will
939 * contain the start record for the checkpoint. Otherwise this write contains
940 * the commit record for the checkpoint.
941 */
942 void
943 xlog_cil_set_ctx_write_state(
944 	struct xfs_cil_ctx	*ctx,
945 	struct xlog_in_core	*iclog)
946 {
947 	struct xfs_cil		*cil = ctx->cil;
948 	xfs_lsn_t		lsn = be64_to_cpu(iclog->ic_header.h_lsn);
949 
950 	ASSERT(!ctx->commit_lsn);
951 	if (!ctx->start_lsn) {
952 		spin_lock(&cil->xc_push_lock);
953 		/*
954 		 * The LSN we need to pass to the log items on transaction
955 		 * commit is the LSN reported by the first log vector write, not
956 		 * the commit lsn. If we use the commit record lsn then we can
957 		 * move the grant write head beyond the tail LSN and overwrite
958 		 * it.
959 		 */
960 		ctx->start_lsn = lsn;
961 		wake_up_all(&cil->xc_start_wait);
962 		spin_unlock(&cil->xc_push_lock);
963 
964 		/*
965 		 * Make sure the metadata we are about to overwrite in the log
966 		 * has been flushed to stable storage before this iclog is
967 		 * issued.
968 		 */
969 		spin_lock(&cil->xc_log->l_icloglock);
970 		iclog->ic_flags |= XLOG_ICL_NEED_FLUSH;
971 		spin_unlock(&cil->xc_log->l_icloglock);
972 		return;
973 	}
974 
975 	/*
976 	 * Take a reference to the iclog for the context so that we still hold
977 	 * it when xlog_write is done and has released it. This means the
978 	 * context controls when the iclog is released for IO.
979 	 */
980 	atomic_inc(&iclog->ic_refcnt);
981 
982 	/*
983 	 * xlog_state_get_iclog_space() guarantees there is enough space in the
984 	 * iclog for an entire commit record, so we can attach the context
985 	 * callbacks now.  This needs to be done before we make the commit_lsn
986 	 * visible to waiters so that checkpoints with commit records in the
987 	 * same iclog order their IO completion callbacks in the same order that
988 	 * the commit records appear in the iclog.
989 	 */
990 	spin_lock(&cil->xc_log->l_icloglock);
991 	list_add_tail(&ctx->iclog_entry, &iclog->ic_callbacks);
992 	spin_unlock(&cil->xc_log->l_icloglock);
993 
994 	/*
995 	 * Now we can record the commit LSN and wake anyone waiting for this
996 	 * sequence to have the ordered commit record assigned to a physical
997 	 * location in the log.
998 	 */
999 	spin_lock(&cil->xc_push_lock);
1000 	ctx->commit_iclog = iclog;
1001 	ctx->commit_lsn = lsn;
1002 	wake_up_all(&cil->xc_commit_wait);
1003 	spin_unlock(&cil->xc_push_lock);
1004 }
1005 
1006 
1007 /*
1008  * Ensure that the order of log writes follows checkpoint sequence order. This
1009  * relies on the context LSN being zero until the log write has guaranteed the
1010  * LSN that the log write will start at via xlog_state_get_iclog_space().
1011  */
1012 enum _record_type {
1013 	_START_RECORD,
1014 	_COMMIT_RECORD,
1015 };
1016 
1017 static int
1018 xlog_cil_order_write(
1019 	struct xfs_cil		*cil,
1020 	xfs_csn_t		sequence,
1021 	enum _record_type	record)
1022 {
1023 	struct xfs_cil_ctx	*ctx;
1024 
1025 restart:
1026 	spin_lock(&cil->xc_push_lock);
1027 	list_for_each_entry(ctx, &cil->xc_committing, committing) {
1028 		/*
1029 		 * Avoid getting stuck in this loop because we were woken by the
1030 		 * shutdown, but then went back to sleep once already in the
1031 		 * shutdown state.
1032 		 */
1033 		if (xlog_is_shutdown(cil->xc_log)) {
1034 			spin_unlock(&cil->xc_push_lock);
1035 			return -EIO;
1036 		}
1037 
1038 		/*
1039 		 * Higher sequences will wait for this one so skip them.
1040 		 * Don't wait for our own sequence, either.
1041 		 */
1042 		if (ctx->sequence >= sequence)
1043 			continue;
1044 
1045 		/* Wait until the LSN for the record has been recorded. */
1046 		switch (record) {
1047 		case _START_RECORD:
1048 			if (!ctx->start_lsn) {
1049 				xlog_wait(&cil->xc_start_wait, &cil->xc_push_lock);
1050 				goto restart;
1051 			}
1052 			break;
1053 		case _COMMIT_RECORD:
1054 			if (!ctx->commit_lsn) {
1055 				xlog_wait(&cil->xc_commit_wait, &cil->xc_push_lock);
1056 				goto restart;
1057 			}
1058 			break;
1059 		}
1060 	}
1061 	spin_unlock(&cil->xc_push_lock);
1062 	return 0;
1063 }
1064 
1065 /*
1066  * Write out the log vector change now attached to the CIL context. This will
1067  * write a start record that needs to be strictly ordered in ascending CIL
1068  * sequence order so that log recovery will always use in-order start LSNs when
1069  * replaying checkpoints.
1070  */
1071 static int
1072 xlog_cil_write_chain(
1073 	struct xfs_cil_ctx	*ctx,
1074 	uint32_t		chain_len)
1075 {
1076 	struct xlog		*log = ctx->cil->xc_log;
1077 	int			error;
1078 
1079 	error = xlog_cil_order_write(ctx->cil, ctx->sequence, _START_RECORD);
1080 	if (error)
1081 		return error;
1082 	return xlog_write(log, ctx, &ctx->lv_chain, ctx->ticket, chain_len);
1083 }
1084 
1085 /*
1086  * Write out the commit record of a checkpoint transaction to close off a
1087  * running log write. These commit records are strictly ordered in ascending CIL
1088  * sequence order so that log recovery will always replay the checkpoints in the
1089  * correct order.
1090  */
1091 static int
1092 xlog_cil_write_commit_record(
1093 	struct xfs_cil_ctx	*ctx)
1094 {
1095 	struct xlog		*log = ctx->cil->xc_log;
1096 	struct xlog_op_header	ophdr = {
1097 		.oh_clientid = XFS_TRANSACTION,
1098 		.oh_tid = cpu_to_be32(ctx->ticket->t_tid),
1099 		.oh_flags = XLOG_COMMIT_TRANS,
1100 	};
1101 	struct xfs_log_iovec	reg = {
1102 		.i_addr = &ophdr,
1103 		.i_len = sizeof(struct xlog_op_header),
1104 		.i_type = XLOG_REG_TYPE_COMMIT,
1105 	};
1106 	struct xfs_log_vec	vec = {
1107 		.lv_niovecs = 1,
1108 		.lv_iovecp = &reg,
1109 	};
1110 	int			error;
1111 	LIST_HEAD(lv_chain);
1112 	list_add(&vec.lv_list, &lv_chain);
1113 
1114 	if (xlog_is_shutdown(log))
1115 		return -EIO;
1116 
1117 	error = xlog_cil_order_write(ctx->cil, ctx->sequence, _COMMIT_RECORD);
1118 	if (error)
1119 		return error;
1120 
1121 	/* account for space used by record data */
1122 	ctx->ticket->t_curr_res -= reg.i_len;
1123 	error = xlog_write(log, ctx, &lv_chain, ctx->ticket, reg.i_len);
1124 	if (error)
1125 		xlog_force_shutdown(log, SHUTDOWN_LOG_IO_ERROR);
1126 	return error;
1127 }
1128 
1129 struct xlog_cil_trans_hdr {
1130 	struct xlog_op_header	oph[2];
1131 	struct xfs_trans_header	thdr;
1132 	struct xfs_log_iovec	lhdr[2];
1133 };
1134 
1135 /*
1136  * Build a checkpoint transaction header to begin the journal transaction.  We
1137  * need to account for the space used by the transaction header here as it is
1138  * not accounted for in xlog_write().
1139  *
1140  * This is the only place we write a transaction header, so we also build the
1141  * log opheaders that indicate the start of a log transaction and wrap the
1142  * transaction header. We keep the start record in it's own log vector rather
1143  * than compacting them into a single region as this ends up making the logic
1144  * in xlog_write() for handling empty opheaders for start, commit and unmount
1145  * records much simpler.
1146  */
1147 static void
1148 xlog_cil_build_trans_hdr(
1149 	struct xfs_cil_ctx	*ctx,
1150 	struct xlog_cil_trans_hdr *hdr,
1151 	struct xfs_log_vec	*lvhdr,
1152 	int			num_iovecs)
1153 {
1154 	struct xlog_ticket	*tic = ctx->ticket;
1155 	__be32			tid = cpu_to_be32(tic->t_tid);
1156 
1157 	memset(hdr, 0, sizeof(*hdr));
1158 
1159 	/* Log start record */
1160 	hdr->oph[0].oh_tid = tid;
1161 	hdr->oph[0].oh_clientid = XFS_TRANSACTION;
1162 	hdr->oph[0].oh_flags = XLOG_START_TRANS;
1163 
1164 	/* log iovec region pointer */
1165 	hdr->lhdr[0].i_addr = &hdr->oph[0];
1166 	hdr->lhdr[0].i_len = sizeof(struct xlog_op_header);
1167 	hdr->lhdr[0].i_type = XLOG_REG_TYPE_LRHEADER;
1168 
1169 	/* log opheader */
1170 	hdr->oph[1].oh_tid = tid;
1171 	hdr->oph[1].oh_clientid = XFS_TRANSACTION;
1172 	hdr->oph[1].oh_len = cpu_to_be32(sizeof(struct xfs_trans_header));
1173 
1174 	/* transaction header in host byte order format */
1175 	hdr->thdr.th_magic = XFS_TRANS_HEADER_MAGIC;
1176 	hdr->thdr.th_type = XFS_TRANS_CHECKPOINT;
1177 	hdr->thdr.th_tid = tic->t_tid;
1178 	hdr->thdr.th_num_items = num_iovecs;
1179 
1180 	/* log iovec region pointer */
1181 	hdr->lhdr[1].i_addr = &hdr->oph[1];
1182 	hdr->lhdr[1].i_len = sizeof(struct xlog_op_header) +
1183 				sizeof(struct xfs_trans_header);
1184 	hdr->lhdr[1].i_type = XLOG_REG_TYPE_TRANSHDR;
1185 
1186 	lvhdr->lv_niovecs = 2;
1187 	lvhdr->lv_iovecp = &hdr->lhdr[0];
1188 	lvhdr->lv_bytes = hdr->lhdr[0].i_len + hdr->lhdr[1].i_len;
1189 
1190 	tic->t_curr_res -= lvhdr->lv_bytes;
1191 }
1192 
1193 /*
1194  * CIL item reordering compare function. We want to order in ascending ID order,
1195  * but we want to leave items with the same ID in the order they were added to
1196  * the list. This is important for operations like reflink where we log 4 order
1197  * dependent intents in a single transaction when we overwrite an existing
1198  * shared extent with a new shared extent. i.e. BUI(unmap), CUI(drop),
1199  * CUI (inc), BUI(remap)...
1200  */
1201 static int
1202 xlog_cil_order_cmp(
1203 	void			*priv,
1204 	const struct list_head	*a,
1205 	const struct list_head	*b)
1206 {
1207 	struct xfs_log_vec	*l1 = container_of(a, struct xfs_log_vec, lv_list);
1208 	struct xfs_log_vec	*l2 = container_of(b, struct xfs_log_vec, lv_list);
1209 
1210 	return l1->lv_order_id > l2->lv_order_id;
1211 }
1212 
1213 /*
1214  * Pull all the log vectors off the items in the CIL, and remove the items from
1215  * the CIL. We don't need the CIL lock here because it's only needed on the
1216  * transaction commit side which is currently locked out by the flush lock.
1217  *
1218  * If a log item is marked with a whiteout, we do not need to write it to the
1219  * journal and so we just move them to the whiteout list for the caller to
1220  * dispose of appropriately.
1221  */
1222 static void
1223 xlog_cil_build_lv_chain(
1224 	struct xfs_cil_ctx	*ctx,
1225 	struct list_head	*whiteouts,
1226 	uint32_t		*num_iovecs,
1227 	uint32_t		*num_bytes)
1228 {
1229 	while (!list_empty(&ctx->log_items)) {
1230 		struct xfs_log_item	*item;
1231 		struct xfs_log_vec	*lv;
1232 
1233 		item = list_first_entry(&ctx->log_items,
1234 					struct xfs_log_item, li_cil);
1235 
1236 		if (test_bit(XFS_LI_WHITEOUT, &item->li_flags)) {
1237 			list_move(&item->li_cil, whiteouts);
1238 			trace_xfs_cil_whiteout_skip(item);
1239 			continue;
1240 		}
1241 
1242 		lv = item->li_lv;
1243 		lv->lv_order_id = item->li_order_id;
1244 
1245 		/* we don't write ordered log vectors */
1246 		if (lv->lv_buf_len != XFS_LOG_VEC_ORDERED)
1247 			*num_bytes += lv->lv_bytes;
1248 		*num_iovecs += lv->lv_niovecs;
1249 		list_add_tail(&lv->lv_list, &ctx->lv_chain);
1250 
1251 		list_del_init(&item->li_cil);
1252 		item->li_order_id = 0;
1253 		item->li_lv = NULL;
1254 	}
1255 }
1256 
1257 static void
1258 xlog_cil_cleanup_whiteouts(
1259 	struct list_head	*whiteouts)
1260 {
1261 	while (!list_empty(whiteouts)) {
1262 		struct xfs_log_item *item = list_first_entry(whiteouts,
1263 						struct xfs_log_item, li_cil);
1264 		list_del_init(&item->li_cil);
1265 		trace_xfs_cil_whiteout_unpin(item);
1266 		item->li_ops->iop_unpin(item, 1);
1267 	}
1268 }
1269 
1270 /*
1271  * Push the Committed Item List to the log.
1272  *
1273  * If the current sequence is the same as xc_push_seq we need to do a flush. If
1274  * xc_push_seq is less than the current sequence, then it has already been
1275  * flushed and we don't need to do anything - the caller will wait for it to
1276  * complete if necessary.
1277  *
1278  * xc_push_seq is checked unlocked against the sequence number for a match.
1279  * Hence we can allow log forces to run racily and not issue pushes for the
1280  * same sequence twice.  If we get a race between multiple pushes for the same
1281  * sequence they will block on the first one and then abort, hence avoiding
1282  * needless pushes.
1283  *
1284  * This runs from a workqueue so it does not inherent any specific memory
1285  * allocation context. However, we do not want to block on memory reclaim
1286  * recursing back into the filesystem because this push may have been triggered
1287  * by memory reclaim itself. Hence we really need to run under full GFP_NOFS
1288  * contraints here.
1289  */
1290 static void
1291 xlog_cil_push_work(
1292 	struct work_struct	*work)
1293 {
1294 	unsigned int		nofs_flags = memalloc_nofs_save();
1295 	struct xfs_cil_ctx	*ctx =
1296 		container_of(work, struct xfs_cil_ctx, push_work);
1297 	struct xfs_cil		*cil = ctx->cil;
1298 	struct xlog		*log = cil->xc_log;
1299 	struct xfs_cil_ctx	*new_ctx;
1300 	int			num_iovecs = 0;
1301 	int			num_bytes = 0;
1302 	int			error = 0;
1303 	struct xlog_cil_trans_hdr thdr;
1304 	struct xfs_log_vec	lvhdr = {};
1305 	xfs_csn_t		push_seq;
1306 	bool			push_commit_stable;
1307 	LIST_HEAD		(whiteouts);
1308 	struct xlog_ticket	*ticket;
1309 
1310 	new_ctx = xlog_cil_ctx_alloc();
1311 	new_ctx->ticket = xlog_cil_ticket_alloc(log);
1312 
1313 	down_write(&cil->xc_ctx_lock);
1314 
1315 	spin_lock(&cil->xc_push_lock);
1316 	push_seq = cil->xc_push_seq;
1317 	ASSERT(push_seq <= ctx->sequence);
1318 	push_commit_stable = cil->xc_push_commit_stable;
1319 	cil->xc_push_commit_stable = false;
1320 
1321 	/*
1322 	 * As we are about to switch to a new, empty CIL context, we no longer
1323 	 * need to throttle tasks on CIL space overruns. Wake any waiters that
1324 	 * the hard push throttle may have caught so they can start committing
1325 	 * to the new context. The ctx->xc_push_lock provides the serialisation
1326 	 * necessary for safely using the lockless waitqueue_active() check in
1327 	 * this context.
1328 	 */
1329 	if (waitqueue_active(&cil->xc_push_wait))
1330 		wake_up_all(&cil->xc_push_wait);
1331 
1332 	xlog_cil_push_pcp_aggregate(cil, ctx);
1333 
1334 	/*
1335 	 * Check if we've anything to push. If there is nothing, then we don't
1336 	 * move on to a new sequence number and so we have to be able to push
1337 	 * this sequence again later.
1338 	 */
1339 	if (test_bit(XLOG_CIL_EMPTY, &cil->xc_flags)) {
1340 		cil->xc_push_seq = 0;
1341 		spin_unlock(&cil->xc_push_lock);
1342 		goto out_skip;
1343 	}
1344 
1345 
1346 	/* check for a previously pushed sequence */
1347 	if (push_seq < ctx->sequence) {
1348 		spin_unlock(&cil->xc_push_lock);
1349 		goto out_skip;
1350 	}
1351 
1352 	/*
1353 	 * We are now going to push this context, so add it to the committing
1354 	 * list before we do anything else. This ensures that anyone waiting on
1355 	 * this push can easily detect the difference between a "push in
1356 	 * progress" and "CIL is empty, nothing to do".
1357 	 *
1358 	 * IOWs, a wait loop can now check for:
1359 	 *	the current sequence not being found on the committing list;
1360 	 *	an empty CIL; and
1361 	 *	an unchanged sequence number
1362 	 * to detect a push that had nothing to do and therefore does not need
1363 	 * waiting on. If the CIL is not empty, we get put on the committing
1364 	 * list before emptying the CIL and bumping the sequence number. Hence
1365 	 * an empty CIL and an unchanged sequence number means we jumped out
1366 	 * above after doing nothing.
1367 	 *
1368 	 * Hence the waiter will either find the commit sequence on the
1369 	 * committing list or the sequence number will be unchanged and the CIL
1370 	 * still dirty. In that latter case, the push has not yet started, and
1371 	 * so the waiter will have to continue trying to check the CIL
1372 	 * committing list until it is found. In extreme cases of delay, the
1373 	 * sequence may fully commit between the attempts the wait makes to wait
1374 	 * on the commit sequence.
1375 	 */
1376 	list_add(&ctx->committing, &cil->xc_committing);
1377 	spin_unlock(&cil->xc_push_lock);
1378 
1379 	xlog_cil_build_lv_chain(ctx, &whiteouts, &num_iovecs, &num_bytes);
1380 
1381 	/*
1382 	 * Switch the contexts so we can drop the context lock and move out
1383 	 * of a shared context. We can't just go straight to the commit record,
1384 	 * though - we need to synchronise with previous and future commits so
1385 	 * that the commit records are correctly ordered in the log to ensure
1386 	 * that we process items during log IO completion in the correct order.
1387 	 *
1388 	 * For example, if we get an EFI in one checkpoint and the EFD in the
1389 	 * next (e.g. due to log forces), we do not want the checkpoint with
1390 	 * the EFD to be committed before the checkpoint with the EFI.  Hence
1391 	 * we must strictly order the commit records of the checkpoints so
1392 	 * that: a) the checkpoint callbacks are attached to the iclogs in the
1393 	 * correct order; and b) the checkpoints are replayed in correct order
1394 	 * in log recovery.
1395 	 *
1396 	 * Hence we need to add this context to the committing context list so
1397 	 * that higher sequences will wait for us to write out a commit record
1398 	 * before they do.
1399 	 *
1400 	 * xfs_log_force_seq requires us to mirror the new sequence into the cil
1401 	 * structure atomically with the addition of this sequence to the
1402 	 * committing list. This also ensures that we can do unlocked checks
1403 	 * against the current sequence in log forces without risking
1404 	 * deferencing a freed context pointer.
1405 	 */
1406 	spin_lock(&cil->xc_push_lock);
1407 	xlog_cil_ctx_switch(cil, new_ctx);
1408 	spin_unlock(&cil->xc_push_lock);
1409 	up_write(&cil->xc_ctx_lock);
1410 
1411 	/*
1412 	 * Sort the log vector chain before we add the transaction headers.
1413 	 * This ensures we always have the transaction headers at the start
1414 	 * of the chain.
1415 	 */
1416 	list_sort(NULL, &ctx->lv_chain, xlog_cil_order_cmp);
1417 
1418 	/*
1419 	 * Build a checkpoint transaction header and write it to the log to
1420 	 * begin the transaction. We need to account for the space used by the
1421 	 * transaction header here as it is not accounted for in xlog_write().
1422 	 * Add the lvhdr to the head of the lv chain we pass to xlog_write() so
1423 	 * it gets written into the iclog first.
1424 	 */
1425 	xlog_cil_build_trans_hdr(ctx, &thdr, &lvhdr, num_iovecs);
1426 	num_bytes += lvhdr.lv_bytes;
1427 	list_add(&lvhdr.lv_list, &ctx->lv_chain);
1428 
1429 	/*
1430 	 * Take the lvhdr back off the lv_chain immediately after calling
1431 	 * xlog_cil_write_chain() as it should not be passed to log IO
1432 	 * completion.
1433 	 */
1434 	error = xlog_cil_write_chain(ctx, num_bytes);
1435 	list_del(&lvhdr.lv_list);
1436 	if (error)
1437 		goto out_abort_free_ticket;
1438 
1439 	error = xlog_cil_write_commit_record(ctx);
1440 	if (error)
1441 		goto out_abort_free_ticket;
1442 
1443 	/*
1444 	 * Grab the ticket from the ctx so we can ungrant it after releasing the
1445 	 * commit_iclog. The ctx may be freed by the time we return from
1446 	 * releasing the commit_iclog (i.e. checkpoint has been completed and
1447 	 * callback run) so we can't reference the ctx after the call to
1448 	 * xlog_state_release_iclog().
1449 	 */
1450 	ticket = ctx->ticket;
1451 
1452 	/*
1453 	 * If the checkpoint spans multiple iclogs, wait for all previous iclogs
1454 	 * to complete before we submit the commit_iclog. We can't use state
1455 	 * checks for this - ACTIVE can be either a past completed iclog or a
1456 	 * future iclog being filled, while WANT_SYNC through SYNC_DONE can be a
1457 	 * past or future iclog awaiting IO or ordered IO completion to be run.
1458 	 * In the latter case, if it's a future iclog and we wait on it, the we
1459 	 * will hang because it won't get processed through to ic_force_wait
1460 	 * wakeup until this commit_iclog is written to disk.  Hence we use the
1461 	 * iclog header lsn and compare it to the commit lsn to determine if we
1462 	 * need to wait on iclogs or not.
1463 	 */
1464 	spin_lock(&log->l_icloglock);
1465 	if (ctx->start_lsn != ctx->commit_lsn) {
1466 		xfs_lsn_t	plsn;
1467 
1468 		plsn = be64_to_cpu(ctx->commit_iclog->ic_prev->ic_header.h_lsn);
1469 		if (plsn && XFS_LSN_CMP(plsn, ctx->commit_lsn) < 0) {
1470 			/*
1471 			 * Waiting on ic_force_wait orders the completion of
1472 			 * iclogs older than ic_prev. Hence we only need to wait
1473 			 * on the most recent older iclog here.
1474 			 */
1475 			xlog_wait_on_iclog(ctx->commit_iclog->ic_prev);
1476 			spin_lock(&log->l_icloglock);
1477 		}
1478 
1479 		/*
1480 		 * We need to issue a pre-flush so that the ordering for this
1481 		 * checkpoint is correctly preserved down to stable storage.
1482 		 */
1483 		ctx->commit_iclog->ic_flags |= XLOG_ICL_NEED_FLUSH;
1484 	}
1485 
1486 	/*
1487 	 * The commit iclog must be written to stable storage to guarantee
1488 	 * journal IO vs metadata writeback IO is correctly ordered on stable
1489 	 * storage.
1490 	 *
1491 	 * If the push caller needs the commit to be immediately stable and the
1492 	 * commit_iclog is not yet marked as XLOG_STATE_WANT_SYNC to indicate it
1493 	 * will be written when released, switch it's state to WANT_SYNC right
1494 	 * now.
1495 	 */
1496 	ctx->commit_iclog->ic_flags |= XLOG_ICL_NEED_FUA;
1497 	if (push_commit_stable &&
1498 	    ctx->commit_iclog->ic_state == XLOG_STATE_ACTIVE)
1499 		xlog_state_switch_iclogs(log, ctx->commit_iclog, 0);
1500 	ticket = ctx->ticket;
1501 	xlog_state_release_iclog(log, ctx->commit_iclog, ticket);
1502 
1503 	/* Not safe to reference ctx now! */
1504 
1505 	spin_unlock(&log->l_icloglock);
1506 	xlog_cil_cleanup_whiteouts(&whiteouts);
1507 	xfs_log_ticket_ungrant(log, ticket);
1508 	memalloc_nofs_restore(nofs_flags);
1509 	return;
1510 
1511 out_skip:
1512 	up_write(&cil->xc_ctx_lock);
1513 	xfs_log_ticket_put(new_ctx->ticket);
1514 	kfree(new_ctx);
1515 	memalloc_nofs_restore(nofs_flags);
1516 	return;
1517 
1518 out_abort_free_ticket:
1519 	ASSERT(xlog_is_shutdown(log));
1520 	xlog_cil_cleanup_whiteouts(&whiteouts);
1521 	if (!ctx->commit_iclog) {
1522 		xfs_log_ticket_ungrant(log, ctx->ticket);
1523 		xlog_cil_committed(ctx);
1524 		memalloc_nofs_restore(nofs_flags);
1525 		return;
1526 	}
1527 	spin_lock(&log->l_icloglock);
1528 	ticket = ctx->ticket;
1529 	xlog_state_release_iclog(log, ctx->commit_iclog, ticket);
1530 	/* Not safe to reference ctx now! */
1531 	spin_unlock(&log->l_icloglock);
1532 	xfs_log_ticket_ungrant(log, ticket);
1533 	memalloc_nofs_restore(nofs_flags);
1534 }
1535 
1536 /*
1537  * We need to push CIL every so often so we don't cache more than we can fit in
1538  * the log. The limit really is that a checkpoint can't be more than half the
1539  * log (the current checkpoint is not allowed to overwrite the previous
1540  * checkpoint), but commit latency and memory usage limit this to a smaller
1541  * size.
1542  */
1543 static void
1544 xlog_cil_push_background(
1545 	struct xlog	*log)
1546 {
1547 	struct xfs_cil	*cil = log->l_cilp;
1548 	int		space_used = atomic_read(&cil->xc_ctx->space_used);
1549 
1550 	/*
1551 	 * The cil won't be empty because we are called while holding the
1552 	 * context lock so whatever we added to the CIL will still be there.
1553 	 */
1554 	ASSERT(!test_bit(XLOG_CIL_EMPTY, &cil->xc_flags));
1555 
1556 	/*
1557 	 * We are done if:
1558 	 * - we haven't used up all the space available yet; or
1559 	 * - we've already queued up a push; and
1560 	 * - we're not over the hard limit; and
1561 	 * - nothing has been over the hard limit.
1562 	 *
1563 	 * If so, we don't need to take the push lock as there's nothing to do.
1564 	 */
1565 	if (space_used < XLOG_CIL_SPACE_LIMIT(log) ||
1566 	    (cil->xc_push_seq == cil->xc_current_sequence &&
1567 	     space_used < XLOG_CIL_BLOCKING_SPACE_LIMIT(log) &&
1568 	     !waitqueue_active(&cil->xc_push_wait))) {
1569 		up_read(&cil->xc_ctx_lock);
1570 		return;
1571 	}
1572 
1573 	spin_lock(&cil->xc_push_lock);
1574 	if (cil->xc_push_seq < cil->xc_current_sequence) {
1575 		cil->xc_push_seq = cil->xc_current_sequence;
1576 		queue_work(cil->xc_push_wq, &cil->xc_ctx->push_work);
1577 	}
1578 
1579 	/*
1580 	 * Drop the context lock now, we can't hold that if we need to sleep
1581 	 * because we are over the blocking threshold. The push_lock is still
1582 	 * held, so blocking threshold sleep/wakeup is still correctly
1583 	 * serialised here.
1584 	 */
1585 	up_read(&cil->xc_ctx_lock);
1586 
1587 	/*
1588 	 * If we are well over the space limit, throttle the work that is being
1589 	 * done until the push work on this context has begun. Enforce the hard
1590 	 * throttle on all transaction commits once it has been activated, even
1591 	 * if the committing transactions have resulted in the space usage
1592 	 * dipping back down under the hard limit.
1593 	 *
1594 	 * The ctx->xc_push_lock provides the serialisation necessary for safely
1595 	 * calling xlog_cil_over_hard_limit() in this context.
1596 	 */
1597 	if (xlog_cil_over_hard_limit(log, space_used)) {
1598 		trace_xfs_log_cil_wait(log, cil->xc_ctx->ticket);
1599 		ASSERT(space_used < log->l_logsize);
1600 		xlog_wait(&cil->xc_push_wait, &cil->xc_push_lock);
1601 		return;
1602 	}
1603 
1604 	spin_unlock(&cil->xc_push_lock);
1605 
1606 }
1607 
1608 /*
1609  * xlog_cil_push_now() is used to trigger an immediate CIL push to the sequence
1610  * number that is passed. When it returns, the work will be queued for
1611  * @push_seq, but it won't be completed.
1612  *
1613  * If the caller is performing a synchronous force, we will flush the workqueue
1614  * to get previously queued work moving to minimise the wait time they will
1615  * undergo waiting for all outstanding pushes to complete. The caller is
1616  * expected to do the required waiting for push_seq to complete.
1617  *
1618  * If the caller is performing an async push, we need to ensure that the
1619  * checkpoint is fully flushed out of the iclogs when we finish the push. If we
1620  * don't do this, then the commit record may remain sitting in memory in an
1621  * ACTIVE iclog. This then requires another full log force to push to disk,
1622  * which defeats the purpose of having an async, non-blocking CIL force
1623  * mechanism. Hence in this case we need to pass a flag to the push work to
1624  * indicate it needs to flush the commit record itself.
1625  */
1626 static void
1627 xlog_cil_push_now(
1628 	struct xlog	*log,
1629 	xfs_lsn_t	push_seq,
1630 	bool		async)
1631 {
1632 	struct xfs_cil	*cil = log->l_cilp;
1633 
1634 	if (!cil)
1635 		return;
1636 
1637 	ASSERT(push_seq && push_seq <= cil->xc_current_sequence);
1638 
1639 	/* start on any pending background push to minimise wait time on it */
1640 	if (!async)
1641 		flush_workqueue(cil->xc_push_wq);
1642 
1643 	spin_lock(&cil->xc_push_lock);
1644 
1645 	/*
1646 	 * If this is an async flush request, we always need to set the
1647 	 * xc_push_commit_stable flag even if something else has already queued
1648 	 * a push. The flush caller is asking for the CIL to be on stable
1649 	 * storage when the next push completes, so regardless of who has queued
1650 	 * the push, the flush requires stable semantics from it.
1651 	 */
1652 	cil->xc_push_commit_stable = async;
1653 
1654 	/*
1655 	 * If the CIL is empty or we've already pushed the sequence then
1656 	 * there's no more work that we need to do.
1657 	 */
1658 	if (test_bit(XLOG_CIL_EMPTY, &cil->xc_flags) ||
1659 	    push_seq <= cil->xc_push_seq) {
1660 		spin_unlock(&cil->xc_push_lock);
1661 		return;
1662 	}
1663 
1664 	cil->xc_push_seq = push_seq;
1665 	queue_work(cil->xc_push_wq, &cil->xc_ctx->push_work);
1666 	spin_unlock(&cil->xc_push_lock);
1667 }
1668 
1669 bool
1670 xlog_cil_empty(
1671 	struct xlog	*log)
1672 {
1673 	struct xfs_cil	*cil = log->l_cilp;
1674 	bool		empty = false;
1675 
1676 	spin_lock(&cil->xc_push_lock);
1677 	if (test_bit(XLOG_CIL_EMPTY, &cil->xc_flags))
1678 		empty = true;
1679 	spin_unlock(&cil->xc_push_lock);
1680 	return empty;
1681 }
1682 
1683 /*
1684  * If there are intent done items in this transaction and the related intent was
1685  * committed in the current (same) CIL checkpoint, we don't need to write either
1686  * the intent or intent done item to the journal as the change will be
1687  * journalled atomically within this checkpoint. As we cannot remove items from
1688  * the CIL here, mark the related intent with a whiteout so that the CIL push
1689  * can remove it rather than writing it to the journal. Then remove the intent
1690  * done item from the current transaction and release it so it doesn't get put
1691  * into the CIL at all.
1692  */
1693 static uint32_t
1694 xlog_cil_process_intents(
1695 	struct xfs_cil		*cil,
1696 	struct xfs_trans	*tp)
1697 {
1698 	struct xfs_log_item	*lip, *ilip, *next;
1699 	uint32_t		len = 0;
1700 
1701 	list_for_each_entry_safe(lip, next, &tp->t_items, li_trans) {
1702 		if (!(lip->li_ops->flags & XFS_ITEM_INTENT_DONE))
1703 			continue;
1704 
1705 		ilip = lip->li_ops->iop_intent(lip);
1706 		if (!ilip || !xlog_item_in_current_chkpt(cil, ilip))
1707 			continue;
1708 		set_bit(XFS_LI_WHITEOUT, &ilip->li_flags);
1709 		trace_xfs_cil_whiteout_mark(ilip);
1710 		len += ilip->li_lv->lv_bytes;
1711 		kvfree(ilip->li_lv);
1712 		ilip->li_lv = NULL;
1713 
1714 		xfs_trans_del_item(lip);
1715 		lip->li_ops->iop_release(lip);
1716 	}
1717 	return len;
1718 }
1719 
1720 /*
1721  * Commit a transaction with the given vector to the Committed Item List.
1722  *
1723  * To do this, we need to format the item, pin it in memory if required and
1724  * account for the space used by the transaction. Once we have done that we
1725  * need to release the unused reservation for the transaction, attach the
1726  * transaction to the checkpoint context so we carry the busy extents through
1727  * to checkpoint completion, and then unlock all the items in the transaction.
1728  *
1729  * Called with the context lock already held in read mode to lock out
1730  * background commit, returns without it held once background commits are
1731  * allowed again.
1732  */
1733 void
1734 xlog_cil_commit(
1735 	struct xlog		*log,
1736 	struct xfs_trans	*tp,
1737 	xfs_csn_t		*commit_seq,
1738 	bool			regrant)
1739 {
1740 	struct xfs_cil		*cil = log->l_cilp;
1741 	struct xfs_log_item	*lip, *next;
1742 	uint32_t		released_space = 0;
1743 
1744 	/*
1745 	 * Do all necessary memory allocation before we lock the CIL.
1746 	 * This ensures the allocation does not deadlock with a CIL
1747 	 * push in memory reclaim (e.g. from kswapd).
1748 	 */
1749 	xlog_cil_alloc_shadow_bufs(log, tp);
1750 
1751 	/* lock out background commit */
1752 	down_read(&cil->xc_ctx_lock);
1753 
1754 	if (tp->t_flags & XFS_TRANS_HAS_INTENT_DONE)
1755 		released_space = xlog_cil_process_intents(cil, tp);
1756 
1757 	xlog_cil_insert_items(log, tp, released_space);
1758 
1759 	if (regrant && !xlog_is_shutdown(log))
1760 		xfs_log_ticket_regrant(log, tp->t_ticket);
1761 	else
1762 		xfs_log_ticket_ungrant(log, tp->t_ticket);
1763 	tp->t_ticket = NULL;
1764 	xfs_trans_unreserve_and_mod_sb(tp);
1765 
1766 	/*
1767 	 * Once all the items of the transaction have been copied to the CIL,
1768 	 * the items can be unlocked and possibly freed.
1769 	 *
1770 	 * This needs to be done before we drop the CIL context lock because we
1771 	 * have to update state in the log items and unlock them before they go
1772 	 * to disk. If we don't, then the CIL checkpoint can race with us and
1773 	 * we can run checkpoint completion before we've updated and unlocked
1774 	 * the log items. This affects (at least) processing of stale buffers,
1775 	 * inodes and EFIs.
1776 	 */
1777 	trace_xfs_trans_commit_items(tp, _RET_IP_);
1778 	list_for_each_entry_safe(lip, next, &tp->t_items, li_trans) {
1779 		xfs_trans_del_item(lip);
1780 		if (lip->li_ops->iop_committing)
1781 			lip->li_ops->iop_committing(lip, cil->xc_ctx->sequence);
1782 	}
1783 	if (commit_seq)
1784 		*commit_seq = cil->xc_ctx->sequence;
1785 
1786 	/* xlog_cil_push_background() releases cil->xc_ctx_lock */
1787 	xlog_cil_push_background(log);
1788 }
1789 
1790 /*
1791  * Flush the CIL to stable storage but don't wait for it to complete. This
1792  * requires the CIL push to ensure the commit record for the push hits the disk,
1793  * but otherwise is no different to a push done from a log force.
1794  */
1795 void
1796 xlog_cil_flush(
1797 	struct xlog	*log)
1798 {
1799 	xfs_csn_t	seq = log->l_cilp->xc_current_sequence;
1800 
1801 	trace_xfs_log_force(log->l_mp, seq, _RET_IP_);
1802 	xlog_cil_push_now(log, seq, true);
1803 
1804 	/*
1805 	 * If the CIL is empty, make sure that any previous checkpoint that may
1806 	 * still be in an active iclog is pushed to stable storage.
1807 	 */
1808 	if (test_bit(XLOG_CIL_EMPTY, &log->l_cilp->xc_flags))
1809 		xfs_log_force(log->l_mp, 0);
1810 }
1811 
1812 /*
1813  * Conditionally push the CIL based on the sequence passed in.
1814  *
1815  * We only need to push if we haven't already pushed the sequence number given.
1816  * Hence the only time we will trigger a push here is if the push sequence is
1817  * the same as the current context.
1818  *
1819  * We return the current commit lsn to allow the callers to determine if a
1820  * iclog flush is necessary following this call.
1821  */
1822 xfs_lsn_t
1823 xlog_cil_force_seq(
1824 	struct xlog	*log,
1825 	xfs_csn_t	sequence)
1826 {
1827 	struct xfs_cil		*cil = log->l_cilp;
1828 	struct xfs_cil_ctx	*ctx;
1829 	xfs_lsn_t		commit_lsn = NULLCOMMITLSN;
1830 
1831 	ASSERT(sequence <= cil->xc_current_sequence);
1832 
1833 	if (!sequence)
1834 		sequence = cil->xc_current_sequence;
1835 	trace_xfs_log_force(log->l_mp, sequence, _RET_IP_);
1836 
1837 	/*
1838 	 * check to see if we need to force out the current context.
1839 	 * xlog_cil_push() handles racing pushes for the same sequence,
1840 	 * so no need to deal with it here.
1841 	 */
1842 restart:
1843 	xlog_cil_push_now(log, sequence, false);
1844 
1845 	/*
1846 	 * See if we can find a previous sequence still committing.
1847 	 * We need to wait for all previous sequence commits to complete
1848 	 * before allowing the force of push_seq to go ahead. Hence block
1849 	 * on commits for those as well.
1850 	 */
1851 	spin_lock(&cil->xc_push_lock);
1852 	list_for_each_entry(ctx, &cil->xc_committing, committing) {
1853 		/*
1854 		 * Avoid getting stuck in this loop because we were woken by the
1855 		 * shutdown, but then went back to sleep once already in the
1856 		 * shutdown state.
1857 		 */
1858 		if (xlog_is_shutdown(log))
1859 			goto out_shutdown;
1860 		if (ctx->sequence > sequence)
1861 			continue;
1862 		if (!ctx->commit_lsn) {
1863 			/*
1864 			 * It is still being pushed! Wait for the push to
1865 			 * complete, then start again from the beginning.
1866 			 */
1867 			XFS_STATS_INC(log->l_mp, xs_log_force_sleep);
1868 			xlog_wait(&cil->xc_commit_wait, &cil->xc_push_lock);
1869 			goto restart;
1870 		}
1871 		if (ctx->sequence != sequence)
1872 			continue;
1873 		/* found it! */
1874 		commit_lsn = ctx->commit_lsn;
1875 	}
1876 
1877 	/*
1878 	 * The call to xlog_cil_push_now() executes the push in the background.
1879 	 * Hence by the time we have got here it our sequence may not have been
1880 	 * pushed yet. This is true if the current sequence still matches the
1881 	 * push sequence after the above wait loop and the CIL still contains
1882 	 * dirty objects. This is guaranteed by the push code first adding the
1883 	 * context to the committing list before emptying the CIL.
1884 	 *
1885 	 * Hence if we don't find the context in the committing list and the
1886 	 * current sequence number is unchanged then the CIL contents are
1887 	 * significant.  If the CIL is empty, if means there was nothing to push
1888 	 * and that means there is nothing to wait for. If the CIL is not empty,
1889 	 * it means we haven't yet started the push, because if it had started
1890 	 * we would have found the context on the committing list.
1891 	 */
1892 	if (sequence == cil->xc_current_sequence &&
1893 	    !test_bit(XLOG_CIL_EMPTY, &cil->xc_flags)) {
1894 		spin_unlock(&cil->xc_push_lock);
1895 		goto restart;
1896 	}
1897 
1898 	spin_unlock(&cil->xc_push_lock);
1899 	return commit_lsn;
1900 
1901 	/*
1902 	 * We detected a shutdown in progress. We need to trigger the log force
1903 	 * to pass through it's iclog state machine error handling, even though
1904 	 * we are already in a shutdown state. Hence we can't return
1905 	 * NULLCOMMITLSN here as that has special meaning to log forces (i.e.
1906 	 * LSN is already stable), so we return a zero LSN instead.
1907 	 */
1908 out_shutdown:
1909 	spin_unlock(&cil->xc_push_lock);
1910 	return 0;
1911 }
1912 
1913 /*
1914  * Perform initial CIL structure initialisation.
1915  */
1916 int
1917 xlog_cil_init(
1918 	struct xlog		*log)
1919 {
1920 	struct xfs_cil		*cil;
1921 	struct xfs_cil_ctx	*ctx;
1922 	struct xlog_cil_pcp	*cilpcp;
1923 	int			cpu;
1924 
1925 	cil = kzalloc(sizeof(*cil), GFP_KERNEL | __GFP_RETRY_MAYFAIL);
1926 	if (!cil)
1927 		return -ENOMEM;
1928 	/*
1929 	 * Limit the CIL pipeline depth to 4 concurrent works to bound the
1930 	 * concurrency the log spinlocks will be exposed to.
1931 	 */
1932 	cil->xc_push_wq = alloc_workqueue("xfs-cil/%s",
1933 			XFS_WQFLAGS(WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_UNBOUND),
1934 			4, log->l_mp->m_super->s_id);
1935 	if (!cil->xc_push_wq)
1936 		goto out_destroy_cil;
1937 
1938 	cil->xc_log = log;
1939 	cil->xc_pcp = alloc_percpu(struct xlog_cil_pcp);
1940 	if (!cil->xc_pcp)
1941 		goto out_destroy_wq;
1942 
1943 	for_each_possible_cpu(cpu) {
1944 		cilpcp = per_cpu_ptr(cil->xc_pcp, cpu);
1945 		INIT_LIST_HEAD(&cilpcp->busy_extents);
1946 		INIT_LIST_HEAD(&cilpcp->log_items);
1947 	}
1948 
1949 	INIT_LIST_HEAD(&cil->xc_committing);
1950 	spin_lock_init(&cil->xc_push_lock);
1951 	init_waitqueue_head(&cil->xc_push_wait);
1952 	init_rwsem(&cil->xc_ctx_lock);
1953 	init_waitqueue_head(&cil->xc_start_wait);
1954 	init_waitqueue_head(&cil->xc_commit_wait);
1955 	log->l_cilp = cil;
1956 
1957 	ctx = xlog_cil_ctx_alloc();
1958 	xlog_cil_ctx_switch(cil, ctx);
1959 	return 0;
1960 
1961 out_destroy_wq:
1962 	destroy_workqueue(cil->xc_push_wq);
1963 out_destroy_cil:
1964 	kfree(cil);
1965 	return -ENOMEM;
1966 }
1967 
1968 void
1969 xlog_cil_destroy(
1970 	struct xlog	*log)
1971 {
1972 	struct xfs_cil	*cil = log->l_cilp;
1973 
1974 	if (cil->xc_ctx) {
1975 		if (cil->xc_ctx->ticket)
1976 			xfs_log_ticket_put(cil->xc_ctx->ticket);
1977 		kfree(cil->xc_ctx);
1978 	}
1979 
1980 	ASSERT(test_bit(XLOG_CIL_EMPTY, &cil->xc_flags));
1981 	free_percpu(cil->xc_pcp);
1982 	destroy_workqueue(cil->xc_push_wq);
1983 	kfree(cil);
1984 }
1985 
1986