xref: /linux/fs/xfs/xfs_log.c (revision 3ed1c68307c4ce53256e15b8a8830b12bdba1ff5)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
4  * All Rights Reserved.
5  */
6 #include "xfs.h"
7 #include "xfs_fs.h"
8 #include "xfs_shared.h"
9 #include "xfs_format.h"
10 #include "xfs_log_format.h"
11 #include "xfs_trans_resv.h"
12 #include "xfs_mount.h"
13 #include "xfs_errortag.h"
14 #include "xfs_error.h"
15 #include "xfs_trans.h"
16 #include "xfs_trans_priv.h"
17 #include "xfs_log.h"
18 #include "xfs_log_priv.h"
19 #include "xfs_trace.h"
20 #include "xfs_sysfs.h"
21 #include "xfs_sb.h"
22 #include "xfs_health.h"
23 #include "xfs_zone_alloc.h"
24 
25 struct kmem_cache	*xfs_log_ticket_cache;
26 
27 /* Local miscellaneous function prototypes */
28 STATIC struct xlog *
29 xlog_alloc_log(
30 	struct xfs_mount	*mp,
31 	struct xfs_buftarg	*log_target,
32 	xfs_daddr_t		blk_offset,
33 	int			num_bblks);
34 STATIC void
35 xlog_dealloc_log(
36 	struct xlog		*log);
37 
38 /* local state machine functions */
39 STATIC void xlog_state_done_syncing(
40 	struct xlog_in_core	*iclog);
41 STATIC void xlog_state_do_callback(
42 	struct xlog		*log);
43 STATIC int
44 xlog_state_get_iclog_space(
45 	struct xlog		*log,
46 	int			len,
47 	struct xlog_in_core	**iclog,
48 	struct xlog_ticket	*ticket,
49 	int			*logoffsetp);
50 STATIC void
51 xlog_sync(
52 	struct xlog		*log,
53 	struct xlog_in_core	*iclog,
54 	struct xlog_ticket	*ticket);
55 #if defined(DEBUG)
56 STATIC void
57 xlog_verify_iclog(
58 	struct xlog		*log,
59 	struct xlog_in_core	*iclog,
60 	int			count);
61 STATIC void
62 xlog_verify_tail_lsn(
63 	struct xlog		*log,
64 	struct xlog_in_core	*iclog);
65 #else
66 #define xlog_verify_iclog(a,b,c)
67 #define xlog_verify_tail_lsn(a,b)
68 #endif
69 
70 STATIC int
71 xlog_iclogs_empty(
72 	struct xlog		*log);
73 
74 static int
75 xfs_log_cover(struct xfs_mount *);
76 
77 /*
78  * We need to make sure the buffer pointer returned is naturally aligned for the
79  * biggest basic data type we put into it. We have already accounted for this
80  * padding when sizing the buffer.
81  *
82  * However, this padding does not get written into the log, and hence we have to
83  * track the space used by the log vectors separately to prevent log space hangs
84  * due to inaccurate accounting (i.e. a leak) of the used log space through the
85  * CIL context ticket.
86  *
87  * We also add space for the xlog_op_header that describes this region in the
88  * log. This prepends the data region we return to the caller to copy their data
89  * into, so do all the static initialisation of the ophdr now. Because the ophdr
90  * is not 8 byte aligned, we have to be careful to ensure that we align the
91  * start of the buffer such that the region we return to the call is 8 byte
92  * aligned and packed against the tail of the ophdr.
93  */
94 void *
95 xlog_prepare_iovec(
96 	struct xfs_log_vec	*lv,
97 	struct xfs_log_iovec	**vecp,
98 	uint			type)
99 {
100 	struct xfs_log_iovec	*vec = *vecp;
101 	struct xlog_op_header	*oph;
102 	uint32_t		len;
103 	void			*buf;
104 
105 	if (vec) {
106 		ASSERT(vec - lv->lv_iovecp < lv->lv_niovecs);
107 		vec++;
108 	} else {
109 		vec = &lv->lv_iovecp[0];
110 	}
111 
112 	len = lv->lv_buf_used + sizeof(struct xlog_op_header);
113 	if (!IS_ALIGNED(len, sizeof(uint64_t))) {
114 		lv->lv_buf_used = round_up(len, sizeof(uint64_t)) -
115 					sizeof(struct xlog_op_header);
116 	}
117 
118 	vec->i_type = type;
119 	vec->i_addr = lv->lv_buf + lv->lv_buf_used;
120 
121 	oph = vec->i_addr;
122 	oph->oh_clientid = XFS_TRANSACTION;
123 	oph->oh_res2 = 0;
124 	oph->oh_flags = 0;
125 
126 	buf = vec->i_addr + sizeof(struct xlog_op_header);
127 	ASSERT(IS_ALIGNED((unsigned long)buf, sizeof(uint64_t)));
128 
129 	*vecp = vec;
130 	return buf;
131 }
132 
133 static inline void
134 xlog_grant_sub_space(
135 	struct xlog_grant_head	*head,
136 	int64_t			bytes)
137 {
138 	atomic64_sub(bytes, &head->grant);
139 }
140 
141 static inline void
142 xlog_grant_add_space(
143 	struct xlog_grant_head	*head,
144 	int64_t			bytes)
145 {
146 	atomic64_add(bytes, &head->grant);
147 }
148 
149 static void
150 xlog_grant_head_init(
151 	struct xlog_grant_head	*head)
152 {
153 	atomic64_set(&head->grant, 0);
154 	INIT_LIST_HEAD(&head->waiters);
155 	spin_lock_init(&head->lock);
156 }
157 
158 void
159 xlog_grant_return_space(
160 	struct xlog	*log,
161 	xfs_lsn_t	old_head,
162 	xfs_lsn_t	new_head)
163 {
164 	int64_t		diff = xlog_lsn_sub(log, new_head, old_head);
165 
166 	xlog_grant_sub_space(&log->l_reserve_head, diff);
167 	xlog_grant_sub_space(&log->l_write_head, diff);
168 }
169 
170 /*
171  * Return the space in the log between the tail and the head.  In the case where
172  * we have overrun available reservation space, return 0. The memory barrier
173  * pairs with the smp_wmb() in xlog_cil_ail_insert() to ensure that grant head
174  * vs tail space updates are seen in the correct order and hence avoid
175  * transients as space is transferred from the grant heads to the AIL on commit
176  * completion.
177  */
178 static uint64_t
179 xlog_grant_space_left(
180 	struct xlog		*log,
181 	struct xlog_grant_head	*head)
182 {
183 	int64_t			free_bytes;
184 
185 	smp_rmb();	/* paired with smp_wmb in xlog_cil_ail_insert() */
186 	free_bytes = log->l_logsize - READ_ONCE(log->l_tail_space) -
187 			atomic64_read(&head->grant);
188 	if (free_bytes > 0)
189 		return free_bytes;
190 	return 0;
191 }
192 
193 STATIC void
194 xlog_grant_head_wake_all(
195 	struct xlog_grant_head	*head)
196 {
197 	struct xlog_ticket	*tic;
198 
199 	spin_lock(&head->lock);
200 	list_for_each_entry(tic, &head->waiters, t_queue)
201 		wake_up_process(tic->t_task);
202 	spin_unlock(&head->lock);
203 }
204 
205 static inline int
206 xlog_ticket_reservation(
207 	struct xlog		*log,
208 	struct xlog_grant_head	*head,
209 	struct xlog_ticket	*tic)
210 {
211 	if (head == &log->l_write_head) {
212 		ASSERT(tic->t_flags & XLOG_TIC_PERM_RESERV);
213 		return tic->t_unit_res;
214 	}
215 
216 	if (tic->t_flags & XLOG_TIC_PERM_RESERV)
217 		return tic->t_unit_res * tic->t_cnt;
218 
219 	return tic->t_unit_res;
220 }
221 
222 STATIC bool
223 xlog_grant_head_wake(
224 	struct xlog		*log,
225 	struct xlog_grant_head	*head,
226 	int			*free_bytes)
227 {
228 	struct xlog_ticket	*tic;
229 	int			need_bytes;
230 
231 	list_for_each_entry(tic, &head->waiters, t_queue) {
232 		need_bytes = xlog_ticket_reservation(log, head, tic);
233 		if (*free_bytes < need_bytes)
234 			return false;
235 
236 		*free_bytes -= need_bytes;
237 		trace_xfs_log_grant_wake_up(log, tic);
238 		wake_up_process(tic->t_task);
239 	}
240 
241 	return true;
242 }
243 
244 STATIC int
245 xlog_grant_head_wait(
246 	struct xlog		*log,
247 	struct xlog_grant_head	*head,
248 	struct xlog_ticket	*tic,
249 	int			need_bytes) __releases(&head->lock)
250 					    __acquires(&head->lock)
251 {
252 	list_add_tail(&tic->t_queue, &head->waiters);
253 
254 	do {
255 		if (xlog_is_shutdown(log))
256 			goto shutdown;
257 
258 		__set_current_state(TASK_UNINTERRUPTIBLE);
259 		spin_unlock(&head->lock);
260 
261 		XFS_STATS_INC(log->l_mp, xs_sleep_logspace);
262 
263 		/* Push on the AIL to free up all the log space. */
264 		xfs_ail_push_all(log->l_ailp);
265 
266 		trace_xfs_log_grant_sleep(log, tic);
267 		schedule();
268 		trace_xfs_log_grant_wake(log, tic);
269 
270 		spin_lock(&head->lock);
271 		if (xlog_is_shutdown(log))
272 			goto shutdown;
273 	} while (xlog_grant_space_left(log, head) < need_bytes);
274 
275 	list_del_init(&tic->t_queue);
276 	return 0;
277 shutdown:
278 	list_del_init(&tic->t_queue);
279 	return -EIO;
280 }
281 
282 /*
283  * Atomically get the log space required for a log ticket.
284  *
285  * Once a ticket gets put onto head->waiters, it will only return after the
286  * needed reservation is satisfied.
287  *
288  * This function is structured so that it has a lock free fast path. This is
289  * necessary because every new transaction reservation will come through this
290  * path. Hence any lock will be globally hot if we take it unconditionally on
291  * every pass.
292  *
293  * As tickets are only ever moved on and off head->waiters under head->lock, we
294  * only need to take that lock if we are going to add the ticket to the queue
295  * and sleep. We can avoid taking the lock if the ticket was never added to
296  * head->waiters because the t_queue list head will be empty and we hold the
297  * only reference to it so it can safely be checked unlocked.
298  */
299 STATIC int
300 xlog_grant_head_check(
301 	struct xlog		*log,
302 	struct xlog_grant_head	*head,
303 	struct xlog_ticket	*tic,
304 	int			*need_bytes)
305 {
306 	int			free_bytes;
307 	int			error = 0;
308 
309 	ASSERT(!xlog_in_recovery(log));
310 
311 	/*
312 	 * If there are other waiters on the queue then give them a chance at
313 	 * logspace before us.  Wake up the first waiters, if we do not wake
314 	 * up all the waiters then go to sleep waiting for more free space,
315 	 * otherwise try to get some space for this transaction.
316 	 */
317 	*need_bytes = xlog_ticket_reservation(log, head, tic);
318 	free_bytes = xlog_grant_space_left(log, head);
319 	if (!list_empty_careful(&head->waiters)) {
320 		spin_lock(&head->lock);
321 		if (!xlog_grant_head_wake(log, head, &free_bytes) ||
322 		    free_bytes < *need_bytes) {
323 			error = xlog_grant_head_wait(log, head, tic,
324 						     *need_bytes);
325 		}
326 		spin_unlock(&head->lock);
327 	} else if (free_bytes < *need_bytes) {
328 		spin_lock(&head->lock);
329 		error = xlog_grant_head_wait(log, head, tic, *need_bytes);
330 		spin_unlock(&head->lock);
331 	}
332 
333 	return error;
334 }
335 
336 bool
337 xfs_log_writable(
338 	struct xfs_mount	*mp)
339 {
340 	/*
341 	 * Do not write to the log on norecovery mounts, if the data or log
342 	 * devices are read-only, or if the filesystem is shutdown. Read-only
343 	 * mounts allow internal writes for log recovery and unmount purposes,
344 	 * so don't restrict that case.
345 	 */
346 	if (xfs_has_norecovery(mp))
347 		return false;
348 	if (xfs_readonly_buftarg(mp->m_ddev_targp))
349 		return false;
350 	if (xfs_readonly_buftarg(mp->m_log->l_targ))
351 		return false;
352 	if (xlog_is_shutdown(mp->m_log))
353 		return false;
354 	return true;
355 }
356 
357 /*
358  * Replenish the byte reservation required by moving the grant write head.
359  */
360 int
361 xfs_log_regrant(
362 	struct xfs_mount	*mp,
363 	struct xlog_ticket	*tic)
364 {
365 	struct xlog		*log = mp->m_log;
366 	int			need_bytes;
367 	int			error = 0;
368 
369 	if (xlog_is_shutdown(log))
370 		return -EIO;
371 
372 	XFS_STATS_INC(mp, xs_try_logspace);
373 
374 	/*
375 	 * This is a new transaction on the ticket, so we need to change the
376 	 * transaction ID so that the next transaction has a different TID in
377 	 * the log. Just add one to the existing tid so that we can see chains
378 	 * of rolling transactions in the log easily.
379 	 */
380 	tic->t_tid++;
381 	tic->t_curr_res = tic->t_unit_res;
382 	if (tic->t_cnt > 0)
383 		return 0;
384 
385 	trace_xfs_log_regrant(log, tic);
386 
387 	error = xlog_grant_head_check(log, &log->l_write_head, tic,
388 				      &need_bytes);
389 	if (error)
390 		goto out_error;
391 
392 	xlog_grant_add_space(&log->l_write_head, need_bytes);
393 	trace_xfs_log_regrant_exit(log, tic);
394 	return 0;
395 
396 out_error:
397 	/*
398 	 * If we are failing, make sure the ticket doesn't have any current
399 	 * reservations.  We don't want to add this back when the ticket/
400 	 * transaction gets cancelled.
401 	 */
402 	tic->t_curr_res = 0;
403 	tic->t_cnt = 0;	/* ungrant will give back unit_res * t_cnt. */
404 	return error;
405 }
406 
407 /*
408  * Reserve log space and return a ticket corresponding to the reservation.
409  *
410  * Each reservation is going to reserve extra space for a log record header.
411  * When writes happen to the on-disk log, we don't subtract the length of the
412  * log record header from any reservation.  By wasting space in each
413  * reservation, we prevent over allocation problems.
414  */
415 int
416 xfs_log_reserve(
417 	struct xfs_mount	*mp,
418 	int			unit_bytes,
419 	int			cnt,
420 	struct xlog_ticket	**ticp,
421 	bool			permanent)
422 {
423 	struct xlog		*log = mp->m_log;
424 	struct xlog_ticket	*tic;
425 	int			need_bytes;
426 	int			error = 0;
427 
428 	if (xlog_is_shutdown(log))
429 		return -EIO;
430 
431 	XFS_STATS_INC(mp, xs_try_logspace);
432 
433 	ASSERT(*ticp == NULL);
434 	tic = xlog_ticket_alloc(log, unit_bytes, cnt, permanent);
435 	*ticp = tic;
436 	trace_xfs_log_reserve(log, tic);
437 	error = xlog_grant_head_check(log, &log->l_reserve_head, tic,
438 				      &need_bytes);
439 	if (error)
440 		goto out_error;
441 
442 	xlog_grant_add_space(&log->l_reserve_head, need_bytes);
443 	xlog_grant_add_space(&log->l_write_head, need_bytes);
444 	trace_xfs_log_reserve_exit(log, tic);
445 	return 0;
446 
447 out_error:
448 	/*
449 	 * If we are failing, make sure the ticket doesn't have any current
450 	 * reservations.  We don't want to add this back when the ticket/
451 	 * transaction gets cancelled.
452 	 */
453 	tic->t_curr_res = 0;
454 	tic->t_cnt = 0;	/* ungrant will give back unit_res * t_cnt. */
455 	return error;
456 }
457 
458 /*
459  * Run all the pending iclog callbacks and wake log force waiters and iclog
460  * space waiters so they can process the newly set shutdown state. We really
461  * don't care what order we process callbacks here because the log is shut down
462  * and so state cannot change on disk anymore. However, we cannot wake waiters
463  * until the callbacks have been processed because we may be in unmount and
464  * we must ensure that all AIL operations the callbacks perform have completed
465  * before we tear down the AIL.
466  *
467  * We avoid processing actively referenced iclogs so that we don't run callbacks
468  * while the iclog owner might still be preparing the iclog for IO submssion.
469  * These will be caught by xlog_state_iclog_release() and call this function
470  * again to process any callbacks that may have been added to that iclog.
471  */
472 static void
473 xlog_state_shutdown_callbacks(
474 	struct xlog		*log)
475 {
476 	struct xlog_in_core	*iclog;
477 	LIST_HEAD(cb_list);
478 
479 	iclog = log->l_iclog;
480 	do {
481 		if (atomic_read(&iclog->ic_refcnt)) {
482 			/* Reference holder will re-run iclog callbacks. */
483 			continue;
484 		}
485 		list_splice_init(&iclog->ic_callbacks, &cb_list);
486 		spin_unlock(&log->l_icloglock);
487 
488 		xlog_cil_process_committed(&cb_list);
489 
490 		spin_lock(&log->l_icloglock);
491 		wake_up_all(&iclog->ic_write_wait);
492 		wake_up_all(&iclog->ic_force_wait);
493 	} while ((iclog = iclog->ic_next) != log->l_iclog);
494 
495 	wake_up_all(&log->l_flush_wait);
496 }
497 
498 /*
499  * Flush iclog to disk if this is the last reference to the given iclog and the
500  * it is in the WANT_SYNC state.
501  *
502  * If XLOG_ICL_NEED_FUA is already set on the iclog, we need to ensure that the
503  * log tail is updated correctly. NEED_FUA indicates that the iclog will be
504  * written to stable storage, and implies that a commit record is contained
505  * within the iclog. We need to ensure that the log tail does not move beyond
506  * the tail that the first commit record in the iclog ordered against, otherwise
507  * correct recovery of that checkpoint becomes dependent on future operations
508  * performed on this iclog.
509  *
510  * Hence if NEED_FUA is set and the current iclog tail lsn is empty, write the
511  * current tail into iclog. Once the iclog tail is set, future operations must
512  * not modify it, otherwise they potentially violate ordering constraints for
513  * the checkpoint commit that wrote the initial tail lsn value. The tail lsn in
514  * the iclog will get zeroed on activation of the iclog after sync, so we
515  * always capture the tail lsn on the iclog on the first NEED_FUA release
516  * regardless of the number of active reference counts on this iclog.
517  */
518 int
519 xlog_state_release_iclog(
520 	struct xlog		*log,
521 	struct xlog_in_core	*iclog,
522 	struct xlog_ticket	*ticket)
523 {
524 	bool			last_ref;
525 
526 	lockdep_assert_held(&log->l_icloglock);
527 
528 	trace_xlog_iclog_release(iclog, _RET_IP_);
529 	/*
530 	 * Grabbing the current log tail needs to be atomic w.r.t. the writing
531 	 * of the tail LSN into the iclog so we guarantee that the log tail does
532 	 * not move between the first time we know that the iclog needs to be
533 	 * made stable and when we eventually submit it.
534 	 */
535 	if ((iclog->ic_state == XLOG_STATE_WANT_SYNC ||
536 	     (iclog->ic_flags & XLOG_ICL_NEED_FUA)) &&
537 	    !iclog->ic_header->h_tail_lsn) {
538 		iclog->ic_header->h_tail_lsn =
539 				cpu_to_be64(atomic64_read(&log->l_tail_lsn));
540 	}
541 
542 	last_ref = atomic_dec_and_test(&iclog->ic_refcnt);
543 
544 	if (xlog_is_shutdown(log)) {
545 		/*
546 		 * If there are no more references to this iclog, process the
547 		 * pending iclog callbacks that were waiting on the release of
548 		 * this iclog.
549 		 */
550 		if (last_ref)
551 			xlog_state_shutdown_callbacks(log);
552 		return -EIO;
553 	}
554 
555 	if (!last_ref)
556 		return 0;
557 
558 	if (iclog->ic_state != XLOG_STATE_WANT_SYNC) {
559 		ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
560 		return 0;
561 	}
562 
563 	iclog->ic_state = XLOG_STATE_SYNCING;
564 	xlog_verify_tail_lsn(log, iclog);
565 	trace_xlog_iclog_syncing(iclog, _RET_IP_);
566 
567 	spin_unlock(&log->l_icloglock);
568 	xlog_sync(log, iclog, ticket);
569 	spin_lock(&log->l_icloglock);
570 	return 0;
571 }
572 
573 /*
574  * Mount a log filesystem
575  *
576  * mp		- ubiquitous xfs mount point structure
577  * log_target	- buftarg of on-disk log device
578  * blk_offset	- Start block # where block size is 512 bytes (BBSIZE)
579  * num_bblocks	- Number of BBSIZE blocks in on-disk log
580  *
581  * Return error or zero.
582  */
583 int
584 xfs_log_mount(
585 	xfs_mount_t		*mp,
586 	struct xfs_buftarg	*log_target,
587 	xfs_daddr_t		blk_offset,
588 	int			num_bblks)
589 {
590 	struct xlog		*log;
591 	int			error = 0;
592 	int			min_logfsbs;
593 
594 	if (!xfs_has_norecovery(mp)) {
595 		xfs_notice(mp, "Mounting V%d Filesystem %pU",
596 			   XFS_SB_VERSION_NUM(&mp->m_sb),
597 			   &mp->m_sb.sb_uuid);
598 	} else {
599 		xfs_notice(mp,
600 "Mounting V%d filesystem %pU in no-recovery mode. Filesystem will be inconsistent.",
601 			   XFS_SB_VERSION_NUM(&mp->m_sb),
602 			   &mp->m_sb.sb_uuid);
603 		ASSERT(xfs_is_readonly(mp));
604 	}
605 
606 	log = xlog_alloc_log(mp, log_target, blk_offset, num_bblks);
607 	if (IS_ERR(log)) {
608 		error = PTR_ERR(log);
609 		goto out;
610 	}
611 	mp->m_log = log;
612 
613 	/*
614 	 * Now that we have set up the log and it's internal geometry
615 	 * parameters, we can validate the given log space and drop a critical
616 	 * message via syslog if the log size is too small. A log that is too
617 	 * small can lead to unexpected situations in transaction log space
618 	 * reservation stage. The superblock verifier has already validated all
619 	 * the other log geometry constraints, so we don't have to check those
620 	 * here.
621 	 *
622 	 * Note: For v4 filesystems, we can't just reject the mount if the
623 	 * validation fails.  This would mean that people would have to
624 	 * downgrade their kernel just to remedy the situation as there is no
625 	 * way to grow the log (short of black magic surgery with xfs_db).
626 	 *
627 	 * We can, however, reject mounts for V5 format filesystems, as the
628 	 * mkfs binary being used to make the filesystem should never create a
629 	 * filesystem with a log that is too small.
630 	 */
631 	min_logfsbs = xfs_log_calc_minimum_size(mp);
632 	if (mp->m_sb.sb_logblocks < min_logfsbs) {
633 		xfs_warn(mp,
634 		"Log size %d blocks too small, minimum size is %d blocks",
635 			 mp->m_sb.sb_logblocks, min_logfsbs);
636 
637 		/*
638 		 * Log check errors are always fatal on v5; or whenever bad
639 		 * metadata leads to a crash.
640 		 */
641 		if (xfs_has_crc(mp)) {
642 			xfs_crit(mp, "AAIEEE! Log failed size checks. Abort!");
643 			ASSERT(0);
644 			error = -EINVAL;
645 			goto out_free_log;
646 		}
647 		xfs_crit(mp, "Log size out of supported range.");
648 		xfs_crit(mp,
649 "Continuing onwards, but if log hangs are experienced then please report this message in the bug report.");
650 	}
651 
652 	/*
653 	 * Initialize the AIL now we have a log.
654 	 */
655 	error = xfs_trans_ail_init(mp);
656 	if (error) {
657 		xfs_warn(mp, "AIL initialisation failed: error %d", error);
658 		goto out_free_log;
659 	}
660 	log->l_ailp = mp->m_ail;
661 
662 	/*
663 	 * skip log recovery on a norecovery mount.  pretend it all
664 	 * just worked.
665 	 */
666 	if (!xfs_has_norecovery(mp)) {
667 		error = xlog_recover(log);
668 		if (error) {
669 			xfs_warn(mp, "log mount/recovery failed: error %d",
670 				error);
671 			xlog_recover_cancel(log);
672 			goto out_destroy_ail;
673 		}
674 	}
675 
676 	error = xfs_sysfs_init(&log->l_kobj, &xfs_log_ktype, &mp->m_kobj,
677 			       "log");
678 	if (error)
679 		goto out_destroy_ail;
680 
681 	/* Normal transactions can now occur */
682 	clear_bit(XLOG_ACTIVE_RECOVERY, &log->l_opstate);
683 
684 	/*
685 	 * Now the log has been fully initialised and we know were our
686 	 * space grant counters are, we can initialise the permanent ticket
687 	 * needed for delayed logging to work.
688 	 */
689 	xlog_cil_init_post_recovery(log);
690 
691 	return 0;
692 
693 out_destroy_ail:
694 	xfs_trans_ail_destroy(mp);
695 out_free_log:
696 	xlog_dealloc_log(log);
697 out:
698 	return error;
699 }
700 
701 /*
702  * Finish the recovery of the file system.  This is separate from the
703  * xfs_log_mount() call, because it depends on the code in xfs_mountfs() to read
704  * in the root and real-time bitmap inodes between calling xfs_log_mount() and
705  * here.
706  *
707  * If we finish recovery successfully, start the background log work. If we are
708  * not doing recovery, then we have a RO filesystem and we don't need to start
709  * it.
710  */
711 int
712 xfs_log_mount_finish(
713 	struct xfs_mount	*mp)
714 {
715 	struct xlog		*log = mp->m_log;
716 	int			error = 0;
717 
718 	if (xfs_has_norecovery(mp)) {
719 		ASSERT(xfs_is_readonly(mp));
720 		return 0;
721 	}
722 
723 	/*
724 	 * During the second phase of log recovery, we need iget and
725 	 * iput to behave like they do for an active filesystem.
726 	 * xfs_fs_drop_inode needs to be able to prevent the deletion
727 	 * of inodes before we're done replaying log items on those
728 	 * inodes.  Turn it off immediately after recovery finishes
729 	 * so that we don't leak the quota inodes if subsequent mount
730 	 * activities fail.
731 	 *
732 	 * We let all inodes involved in redo item processing end up on
733 	 * the LRU instead of being evicted immediately so that if we do
734 	 * something to an unlinked inode, the irele won't cause
735 	 * premature truncation and freeing of the inode, which results
736 	 * in log recovery failure.  We have to evict the unreferenced
737 	 * lru inodes after clearing SB_ACTIVE because we don't
738 	 * otherwise clean up the lru if there's a subsequent failure in
739 	 * xfs_mountfs, which leads to us leaking the inodes if nothing
740 	 * else (e.g. quotacheck) references the inodes before the
741 	 * mount failure occurs.
742 	 */
743 	mp->m_super->s_flags |= SB_ACTIVE;
744 	xfs_log_work_queue(mp);
745 	if (xlog_recovery_needed(log))
746 		error = xlog_recover_finish(log);
747 	mp->m_super->s_flags &= ~SB_ACTIVE;
748 	evict_inodes(mp->m_super);
749 
750 	/*
751 	 * Drain the buffer LRU after log recovery. This is required for v4
752 	 * filesystems to avoid leaving around buffers with NULL verifier ops,
753 	 * but we do it unconditionally to make sure we're always in a clean
754 	 * cache state after mount.
755 	 *
756 	 * Don't push in the error case because the AIL may have pending intents
757 	 * that aren't removed until recovery is cancelled.
758 	 */
759 	if (xlog_recovery_needed(log)) {
760 		if (!error) {
761 			xfs_log_force(mp, XFS_LOG_SYNC);
762 			xfs_ail_push_all_sync(mp->m_ail);
763 		}
764 		xfs_notice(mp, "Ending recovery (logdev: %s)",
765 				mp->m_logname ? mp->m_logname : "internal");
766 	} else {
767 		xfs_info(mp, "Ending clean mount");
768 	}
769 	xfs_buftarg_drain(mp->m_ddev_targp);
770 
771 	clear_bit(XLOG_RECOVERY_NEEDED, &log->l_opstate);
772 
773 	/* Make sure the log is dead if we're returning failure. */
774 	ASSERT(!error || xlog_is_shutdown(log));
775 
776 	return error;
777 }
778 
779 /*
780  * The mount has failed. Cancel the recovery if it hasn't completed and destroy
781  * the log.
782  */
783 void
784 xfs_log_mount_cancel(
785 	struct xfs_mount	*mp)
786 {
787 	xlog_recover_cancel(mp->m_log);
788 	xfs_log_unmount(mp);
789 }
790 
791 /*
792  * Flush out the iclog to disk ensuring that device caches are flushed and
793  * the iclog hits stable storage before any completion waiters are woken.
794  */
795 static inline int
796 xlog_force_iclog(
797 	struct xlog_in_core	*iclog)
798 {
799 	atomic_inc(&iclog->ic_refcnt);
800 	iclog->ic_flags |= XLOG_ICL_NEED_FLUSH | XLOG_ICL_NEED_FUA;
801 	if (iclog->ic_state == XLOG_STATE_ACTIVE)
802 		xlog_state_switch_iclogs(iclog->ic_log, iclog, 0);
803 	return xlog_state_release_iclog(iclog->ic_log, iclog, NULL);
804 }
805 
806 /*
807  * Cycle all the iclogbuf locks to make sure all log IO completion
808  * is done before we tear down these buffers.
809  */
810 static void
811 xlog_wait_iclog_completion(struct xlog *log)
812 {
813 	int		i;
814 	struct xlog_in_core	*iclog = log->l_iclog;
815 
816 	for (i = 0; i < log->l_iclog_bufs; i++) {
817 		down(&iclog->ic_sema);
818 		up(&iclog->ic_sema);
819 		iclog = iclog->ic_next;
820 	}
821 }
822 
823 /*
824  * Wait for the iclog and all prior iclogs to be written disk as required by the
825  * log force state machine. Waiting on ic_force_wait ensures iclog completions
826  * have been ordered and callbacks run before we are woken here, hence
827  * guaranteeing that all the iclogs up to this one are on stable storage.
828  */
829 int
830 xlog_wait_on_iclog(
831 	struct xlog_in_core	*iclog)
832 		__releases(iclog->ic_log->l_icloglock)
833 {
834 	struct xlog		*log = iclog->ic_log;
835 
836 	trace_xlog_iclog_wait_on(iclog, _RET_IP_);
837 	if (!xlog_is_shutdown(log) &&
838 	    iclog->ic_state != XLOG_STATE_ACTIVE &&
839 	    iclog->ic_state != XLOG_STATE_DIRTY) {
840 		XFS_STATS_INC(log->l_mp, xs_log_force_sleep);
841 		xlog_wait(&iclog->ic_force_wait, &log->l_icloglock);
842 	} else {
843 		spin_unlock(&log->l_icloglock);
844 	}
845 
846 	if (xlog_is_shutdown(log))
847 		return -EIO;
848 	return 0;
849 }
850 
851 /*
852  * Write out an unmount record using the ticket provided. We have to account for
853  * the data space used in the unmount ticket as this write is not done from a
854  * transaction context that has already done the accounting for us.
855  */
856 static int
857 xlog_write_unmount_record(
858 	struct xlog		*log,
859 	struct xlog_ticket	*ticket)
860 {
861 	struct  {
862 		struct xlog_op_header ophdr;
863 		struct xfs_unmount_log_format ulf;
864 	} unmount_rec = {
865 		.ophdr = {
866 			.oh_clientid = XFS_LOG,
867 			.oh_tid = cpu_to_be32(ticket->t_tid),
868 			.oh_flags = XLOG_UNMOUNT_TRANS,
869 		},
870 		.ulf = {
871 			.magic = XLOG_UNMOUNT_TYPE,
872 		},
873 	};
874 	struct xfs_log_iovec reg = {
875 		.i_addr = &unmount_rec,
876 		.i_len = sizeof(unmount_rec),
877 		.i_type = XLOG_REG_TYPE_UNMOUNT,
878 	};
879 	struct xfs_log_vec vec = {
880 		.lv_niovecs = 1,
881 		.lv_iovecp = &reg,
882 	};
883 	LIST_HEAD(lv_chain);
884 	list_add(&vec.lv_list, &lv_chain);
885 
886 	BUILD_BUG_ON((sizeof(struct xlog_op_header) +
887 		      sizeof(struct xfs_unmount_log_format)) !=
888 							sizeof(unmount_rec));
889 
890 	/* account for space used by record data */
891 	ticket->t_curr_res -= sizeof(unmount_rec);
892 
893 	return xlog_write(log, NULL, &lv_chain, ticket, reg.i_len);
894 }
895 
896 /*
897  * Mark the filesystem clean by writing an unmount record to the head of the
898  * log.
899  */
900 static void
901 xlog_unmount_write(
902 	struct xlog		*log)
903 {
904 	struct xfs_mount	*mp = log->l_mp;
905 	struct xlog_in_core	*iclog;
906 	struct xlog_ticket	*tic = NULL;
907 	int			error;
908 
909 	error = xfs_log_reserve(mp, 600, 1, &tic, 0);
910 	if (error)
911 		goto out_err;
912 
913 	error = xlog_write_unmount_record(log, tic);
914 	/*
915 	 * At this point, we're umounting anyway, so there's no point in
916 	 * transitioning log state to shutdown. Just continue...
917 	 */
918 out_err:
919 	if (error)
920 		xfs_alert(mp, "%s: unmount record failed", __func__);
921 
922 	spin_lock(&log->l_icloglock);
923 	iclog = log->l_iclog;
924 	error = xlog_force_iclog(iclog);
925 	xlog_wait_on_iclog(iclog);
926 
927 	if (tic) {
928 		trace_xfs_log_umount_write(log, tic);
929 		xfs_log_ticket_ungrant(log, tic);
930 	}
931 }
932 
933 static void
934 xfs_log_unmount_verify_iclog(
935 	struct xlog		*log)
936 {
937 	struct xlog_in_core	*iclog = log->l_iclog;
938 
939 	do {
940 		ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
941 		ASSERT(iclog->ic_offset == 0);
942 	} while ((iclog = iclog->ic_next) != log->l_iclog);
943 }
944 
945 /*
946  * Unmount record used to have a string "Unmount filesystem--" in the
947  * data section where the "Un" was really a magic number (XLOG_UNMOUNT_TYPE).
948  * We just write the magic number now since that particular field isn't
949  * currently architecture converted and "Unmount" is a bit foo.
950  * As far as I know, there weren't any dependencies on the old behaviour.
951  */
952 static void
953 xfs_log_unmount_write(
954 	struct xfs_mount	*mp)
955 {
956 	struct xlog		*log = mp->m_log;
957 
958 	if (!xfs_log_writable(mp))
959 		return;
960 
961 	xfs_log_force(mp, XFS_LOG_SYNC);
962 
963 	if (xlog_is_shutdown(log))
964 		return;
965 
966 	/*
967 	 * If we think the summary counters are bad, avoid writing the unmount
968 	 * record to force log recovery at next mount, after which the summary
969 	 * counters will be recalculated.  Refer to xlog_check_unmount_rec for
970 	 * more details.
971 	 */
972 	if (xfs_fs_has_sickness(mp, XFS_SICK_FS_COUNTERS) ||
973 	    XFS_TEST_ERROR(mp, XFS_ERRTAG_FORCE_SUMMARY_RECALC)) {
974 		xfs_alert(mp, "%s: will fix summary counters at next mount",
975 				__func__);
976 		return;
977 	}
978 
979 	xfs_log_unmount_verify_iclog(log);
980 	xlog_unmount_write(log);
981 }
982 
983 /*
984  * Empty the log for unmount/freeze.
985  *
986  * To do this, we first need to shut down the background log work so it is not
987  * trying to cover the log as we clean up. We then need to unpin all objects in
988  * the log so we can then flush them out. Once they have completed their IO and
989  * run the callbacks removing themselves from the AIL, we can cover the log.
990  */
991 int
992 xfs_log_quiesce(
993 	struct xfs_mount	*mp)
994 {
995 	/*
996 	 * Clear log incompat features since we're quiescing the log.  Report
997 	 * failures, though it's not fatal to have a higher log feature
998 	 * protection level than the log contents actually require.
999 	 */
1000 	if (xfs_clear_incompat_log_features(mp)) {
1001 		int error;
1002 
1003 		error = xfs_sync_sb(mp, false);
1004 		if (error)
1005 			xfs_warn(mp,
1006 	"Failed to clear log incompat features on quiesce");
1007 	}
1008 
1009 	cancel_delayed_work_sync(&mp->m_log->l_work);
1010 	xfs_log_force(mp, XFS_LOG_SYNC);
1011 
1012 	/*
1013 	 * The superblock buffer is uncached and while xfs_ail_push_all_sync()
1014 	 * will push it, xfs_buftarg_wait() will not wait for it. Further,
1015 	 * xfs_buf_iowait() cannot be used because it was pushed with the
1016 	 * XBF_ASYNC flag set, so we need to use a lock/unlock pair to wait for
1017 	 * the IO to complete.
1018 	 */
1019 	xfs_ail_push_all_sync(mp->m_ail);
1020 	xfs_buftarg_wait(mp->m_ddev_targp);
1021 	xfs_buf_lock(mp->m_sb_bp);
1022 	xfs_buf_unlock(mp->m_sb_bp);
1023 
1024 	return xfs_log_cover(mp);
1025 }
1026 
1027 void
1028 xfs_log_clean(
1029 	struct xfs_mount	*mp)
1030 {
1031 	xfs_log_quiesce(mp);
1032 	xfs_log_unmount_write(mp);
1033 }
1034 
1035 /*
1036  * Shut down and release the AIL and Log.
1037  *
1038  * During unmount, we need to ensure we flush all the dirty metadata objects
1039  * from the AIL so that the log is empty before we write the unmount record to
1040  * the log. Once this is done, we can tear down the AIL and the log.
1041  */
1042 void
1043 xfs_log_unmount(
1044 	struct xfs_mount	*mp)
1045 {
1046 	xfs_log_clean(mp);
1047 
1048 	/*
1049 	 * If shutdown has come from iclog IO context, the log
1050 	 * cleaning will have been skipped and so we need to wait
1051 	 * for the iclog to complete shutdown processing before we
1052 	 * tear anything down.
1053 	 */
1054 	xlog_wait_iclog_completion(mp->m_log);
1055 
1056 	xfs_buftarg_drain(mp->m_ddev_targp);
1057 
1058 	xfs_trans_ail_destroy(mp);
1059 
1060 	xfs_sysfs_del(&mp->m_log->l_kobj);
1061 
1062 	xlog_dealloc_log(mp->m_log);
1063 }
1064 
1065 void
1066 xfs_log_item_init(
1067 	struct xfs_mount	*mp,
1068 	struct xfs_log_item	*item,
1069 	int			type,
1070 	const struct xfs_item_ops *ops)
1071 {
1072 	item->li_log = mp->m_log;
1073 	item->li_ailp = mp->m_ail;
1074 	item->li_type = type;
1075 	item->li_ops = ops;
1076 	item->li_lv = NULL;
1077 
1078 	INIT_LIST_HEAD(&item->li_ail);
1079 	INIT_LIST_HEAD(&item->li_cil);
1080 	INIT_LIST_HEAD(&item->li_bio_list);
1081 	INIT_LIST_HEAD(&item->li_trans);
1082 }
1083 
1084 /*
1085  * Wake up processes waiting for log space after we have moved the log tail.
1086  */
1087 void
1088 xfs_log_space_wake(
1089 	struct xfs_mount	*mp)
1090 {
1091 	struct xlog		*log = mp->m_log;
1092 	int			free_bytes;
1093 
1094 	if (xlog_is_shutdown(log))
1095 		return;
1096 
1097 	if (!list_empty_careful(&log->l_write_head.waiters)) {
1098 		ASSERT(!xlog_in_recovery(log));
1099 
1100 		spin_lock(&log->l_write_head.lock);
1101 		free_bytes = xlog_grant_space_left(log, &log->l_write_head);
1102 		xlog_grant_head_wake(log, &log->l_write_head, &free_bytes);
1103 		spin_unlock(&log->l_write_head.lock);
1104 	}
1105 
1106 	if (!list_empty_careful(&log->l_reserve_head.waiters)) {
1107 		ASSERT(!xlog_in_recovery(log));
1108 
1109 		spin_lock(&log->l_reserve_head.lock);
1110 		free_bytes = xlog_grant_space_left(log, &log->l_reserve_head);
1111 		xlog_grant_head_wake(log, &log->l_reserve_head, &free_bytes);
1112 		spin_unlock(&log->l_reserve_head.lock);
1113 	}
1114 }
1115 
1116 /*
1117  * Determine if we have a transaction that has gone to disk that needs to be
1118  * covered. To begin the transition to the idle state firstly the log needs to
1119  * be idle. That means the CIL, the AIL and the iclogs needs to be empty before
1120  * we start attempting to cover the log.
1121  *
1122  * Only if we are then in a state where covering is needed, the caller is
1123  * informed that dummy transactions are required to move the log into the idle
1124  * state.
1125  *
1126  * If there are any items in the AIl or CIL, then we do not want to attempt to
1127  * cover the log as we may be in a situation where there isn't log space
1128  * available to run a dummy transaction and this can lead to deadlocks when the
1129  * tail of the log is pinned by an item that is modified in the CIL.  Hence
1130  * there's no point in running a dummy transaction at this point because we
1131  * can't start trying to idle the log until both the CIL and AIL are empty.
1132  */
1133 static bool
1134 xfs_log_need_covered(
1135 	struct xfs_mount	*mp)
1136 {
1137 	struct xlog		*log = mp->m_log;
1138 	bool			needed = false;
1139 
1140 	if (!xlog_cil_empty(log))
1141 		return false;
1142 
1143 	spin_lock(&log->l_icloglock);
1144 	switch (log->l_covered_state) {
1145 	case XLOG_STATE_COVER_DONE:
1146 	case XLOG_STATE_COVER_DONE2:
1147 	case XLOG_STATE_COVER_IDLE:
1148 		break;
1149 	case XLOG_STATE_COVER_NEED:
1150 	case XLOG_STATE_COVER_NEED2:
1151 		if (xfs_ail_min_lsn(log->l_ailp))
1152 			break;
1153 		if (!xlog_iclogs_empty(log))
1154 			break;
1155 
1156 		needed = true;
1157 		if (log->l_covered_state == XLOG_STATE_COVER_NEED)
1158 			log->l_covered_state = XLOG_STATE_COVER_DONE;
1159 		else
1160 			log->l_covered_state = XLOG_STATE_COVER_DONE2;
1161 		break;
1162 	default:
1163 		needed = true;
1164 		break;
1165 	}
1166 	spin_unlock(&log->l_icloglock);
1167 	return needed;
1168 }
1169 
1170 /*
1171  * Explicitly cover the log. This is similar to background log covering but
1172  * intended for usage in quiesce codepaths. The caller is responsible to ensure
1173  * the log is idle and suitable for covering. The CIL, iclog buffers and AIL
1174  * must all be empty.
1175  */
1176 static int
1177 xfs_log_cover(
1178 	struct xfs_mount	*mp)
1179 {
1180 	int			error = 0;
1181 	bool			need_covered;
1182 
1183 	ASSERT((xlog_cil_empty(mp->m_log) && xlog_iclogs_empty(mp->m_log) &&
1184 	        !xfs_ail_min_lsn(mp->m_log->l_ailp)) ||
1185 		xlog_is_shutdown(mp->m_log));
1186 
1187 	if (!xfs_log_writable(mp))
1188 		return 0;
1189 
1190 	/*
1191 	 * xfs_log_need_covered() is not idempotent because it progresses the
1192 	 * state machine if the log requires covering. Therefore, we must call
1193 	 * this function once and use the result until we've issued an sb sync.
1194 	 * Do so first to make that abundantly clear.
1195 	 *
1196 	 * Fall into the covering sequence if the log needs covering or the
1197 	 * mount has lazy superblock accounting to sync to disk. The sb sync
1198 	 * used for covering accumulates the in-core counters, so covering
1199 	 * handles this for us.
1200 	 */
1201 	need_covered = xfs_log_need_covered(mp);
1202 	if (!need_covered && !xfs_has_lazysbcount(mp))
1203 		return 0;
1204 
1205 	/*
1206 	 * To cover the log, commit the superblock twice (at most) in
1207 	 * independent checkpoints. The first serves as a reference for the
1208 	 * tail pointer. The sync transaction and AIL push empties the AIL and
1209 	 * updates the in-core tail to the LSN of the first checkpoint. The
1210 	 * second commit updates the on-disk tail with the in-core LSN,
1211 	 * covering the log. Push the AIL one more time to leave it empty, as
1212 	 * we found it.
1213 	 */
1214 	do {
1215 		error = xfs_sync_sb(mp, true);
1216 		if (error)
1217 			break;
1218 		xfs_ail_push_all_sync(mp->m_ail);
1219 	} while (xfs_log_need_covered(mp));
1220 
1221 	return error;
1222 }
1223 
1224 static void
1225 xlog_ioend_work(
1226 	struct work_struct	*work)
1227 {
1228 	struct xlog_in_core     *iclog =
1229 		container_of(work, struct xlog_in_core, ic_end_io_work);
1230 	struct xlog		*log = iclog->ic_log;
1231 	int			error;
1232 
1233 	error = blk_status_to_errno(iclog->ic_bio.bi_status);
1234 #ifdef DEBUG
1235 	/* treat writes with injected CRC errors as failed */
1236 	if (iclog->ic_fail_crc)
1237 		error = -EIO;
1238 #endif
1239 
1240 	/*
1241 	 * Race to shutdown the filesystem if we see an error.
1242 	 */
1243 	if (error || XFS_TEST_ERROR(log->l_mp, XFS_ERRTAG_IODONE_IOERR)) {
1244 		xfs_alert(log->l_mp, "log I/O error %d", error);
1245 		xlog_force_shutdown(log, SHUTDOWN_LOG_IO_ERROR);
1246 	}
1247 
1248 	xlog_state_done_syncing(iclog);
1249 	bio_uninit(&iclog->ic_bio);
1250 
1251 	/*
1252 	 * Drop the lock to signal that we are done. Nothing references the
1253 	 * iclog after this, so an unmount waiting on this lock can now tear it
1254 	 * down safely. As such, it is unsafe to reference the iclog after the
1255 	 * unlock as we could race with it being freed.
1256 	 */
1257 	up(&iclog->ic_sema);
1258 }
1259 
1260 /*
1261  * Return size of each in-core log record buffer.
1262  *
1263  * All machines get 8 x 32kB buffers by default, unless tuned otherwise.
1264  *
1265  * If the filesystem blocksize is too large, we may need to choose a
1266  * larger size since the directory code currently logs entire blocks.
1267  */
1268 STATIC void
1269 xlog_get_iclog_buffer_size(
1270 	struct xfs_mount	*mp,
1271 	struct xlog		*log)
1272 {
1273 	if (mp->m_logbufs <= 0)
1274 		mp->m_logbufs = XLOG_MAX_ICLOGS;
1275 	if (mp->m_logbsize <= 0)
1276 		mp->m_logbsize = XLOG_BIG_RECORD_BSIZE;
1277 
1278 	log->l_iclog_bufs = mp->m_logbufs;
1279 	log->l_iclog_size = mp->m_logbsize;
1280 
1281 	/*
1282 	 * Combined size of the log record headers.  The first 32k cycles
1283 	 * are stored directly in the xlog_rec_header, the rest in the
1284 	 * variable number of xlog_rec_ext_headers at its end.
1285 	 */
1286 	log->l_iclog_hsize = struct_size(log->l_iclog->ic_header, h_ext,
1287 		DIV_ROUND_UP(mp->m_logbsize, XLOG_HEADER_CYCLE_SIZE) - 1);
1288 }
1289 
1290 void
1291 xfs_log_work_queue(
1292 	struct xfs_mount        *mp)
1293 {
1294 	queue_delayed_work(mp->m_sync_workqueue, &mp->m_log->l_work,
1295 				msecs_to_jiffies(xfs_syncd_centisecs * 10));
1296 }
1297 
1298 /*
1299  * Clear the log incompat flags if we have the opportunity.
1300  *
1301  * This only happens if we're about to log the second dummy transaction as part
1302  * of covering the log.
1303  */
1304 static inline void
1305 xlog_clear_incompat(
1306 	struct xlog		*log)
1307 {
1308 	struct xfs_mount	*mp = log->l_mp;
1309 
1310 	if (!xfs_sb_has_incompat_log_feature(&mp->m_sb,
1311 				XFS_SB_FEAT_INCOMPAT_LOG_ALL))
1312 		return;
1313 
1314 	if (log->l_covered_state != XLOG_STATE_COVER_DONE2)
1315 		return;
1316 
1317 	xfs_clear_incompat_log_features(mp);
1318 }
1319 
1320 /*
1321  * Every sync period we need to unpin all items in the AIL and push them to
1322  * disk. If there is nothing dirty, then we might need to cover the log to
1323  * indicate that the filesystem is idle.
1324  */
1325 static void
1326 xfs_log_worker(
1327 	struct work_struct	*work)
1328 {
1329 	struct xlog		*log = container_of(to_delayed_work(work),
1330 						struct xlog, l_work);
1331 	struct xfs_mount	*mp = log->l_mp;
1332 
1333 	/* dgc: errors ignored - not fatal and nowhere to report them */
1334 	if (xfs_fs_writable(mp, SB_FREEZE_WRITE) && xfs_log_need_covered(mp)) {
1335 		/*
1336 		 * Dump a transaction into the log that contains no real change.
1337 		 * This is needed to stamp the current tail LSN into the log
1338 		 * during the covering operation.
1339 		 *
1340 		 * We cannot use an inode here for this - that will push dirty
1341 		 * state back up into the VFS and then periodic inode flushing
1342 		 * will prevent log covering from making progress. Hence we
1343 		 * synchronously log the superblock instead to ensure the
1344 		 * superblock is immediately unpinned and can be written back.
1345 		 */
1346 		xlog_clear_incompat(log);
1347 		xfs_sync_sb(mp, true);
1348 	} else
1349 		xfs_log_force(mp, 0);
1350 
1351 	/* start pushing all the metadata that is currently dirty */
1352 	xfs_ail_push_all(mp->m_ail);
1353 
1354 	/* queue us up again */
1355 	xfs_log_work_queue(mp);
1356 }
1357 
1358 /*
1359  * This routine initializes some of the log structure for a given mount point.
1360  * Its primary purpose is to fill in enough, so recovery can occur.  However,
1361  * some other stuff may be filled in too.
1362  */
1363 STATIC struct xlog *
1364 xlog_alloc_log(
1365 	struct xfs_mount	*mp,
1366 	struct xfs_buftarg	*log_target,
1367 	xfs_daddr_t		blk_offset,
1368 	int			num_bblks)
1369 {
1370 	struct xlog		*log;
1371 	struct xlog_in_core	**iclogp;
1372 	struct xlog_in_core	*iclog, *prev_iclog = NULL;
1373 	int			i;
1374 	int			error = -ENOMEM;
1375 	uint			log2_size = 0;
1376 
1377 	log = kzalloc(sizeof(struct xlog), GFP_KERNEL | __GFP_RETRY_MAYFAIL);
1378 	if (!log) {
1379 		xfs_warn(mp, "Log allocation failed: No memory!");
1380 		goto out;
1381 	}
1382 
1383 	log->l_mp	   = mp;
1384 	log->l_targ	   = log_target;
1385 	log->l_logsize     = BBTOB(num_bblks);
1386 	log->l_logBBstart  = blk_offset;
1387 	log->l_logBBsize   = num_bblks;
1388 	log->l_covered_state = XLOG_STATE_COVER_IDLE;
1389 	set_bit(XLOG_ACTIVE_RECOVERY, &log->l_opstate);
1390 	INIT_DELAYED_WORK(&log->l_work, xfs_log_worker);
1391 	INIT_LIST_HEAD(&log->r_dfops);
1392 
1393 	log->l_prev_block  = -1;
1394 	/* log->l_tail_lsn = 0x100000000LL; cycle = 1; current block = 0 */
1395 	xlog_assign_atomic_lsn(&log->l_tail_lsn, 1, 0);
1396 	log->l_curr_cycle  = 1;	    /* 0 is bad since this is initial value */
1397 
1398 	if (xfs_has_logv2(mp) && mp->m_sb.sb_logsunit > 1)
1399 		log->l_iclog_roundoff = mp->m_sb.sb_logsunit;
1400 	else
1401 		log->l_iclog_roundoff = BBSIZE;
1402 
1403 	xlog_grant_head_init(&log->l_reserve_head);
1404 	xlog_grant_head_init(&log->l_write_head);
1405 
1406 	error = -EFSCORRUPTED;
1407 	if (xfs_has_sector(mp)) {
1408 	        log2_size = mp->m_sb.sb_logsectlog;
1409 		if (log2_size < BBSHIFT) {
1410 			xfs_warn(mp, "Log sector size too small (0x%x < 0x%x)",
1411 				log2_size, BBSHIFT);
1412 			goto out_free_log;
1413 		}
1414 
1415 	        log2_size -= BBSHIFT;
1416 		if (log2_size > mp->m_sectbb_log) {
1417 			xfs_warn(mp, "Log sector size too large (0x%x > 0x%x)",
1418 				log2_size, mp->m_sectbb_log);
1419 			goto out_free_log;
1420 		}
1421 
1422 		/* for larger sector sizes, must have v2 or external log */
1423 		if (log2_size && log->l_logBBstart > 0 &&
1424 			    !xfs_has_logv2(mp)) {
1425 			xfs_warn(mp,
1426 		"log sector size (0x%x) invalid for configuration.",
1427 				log2_size);
1428 			goto out_free_log;
1429 		}
1430 	}
1431 	log->l_sectBBsize = 1 << log2_size;
1432 
1433 	xlog_get_iclog_buffer_size(mp, log);
1434 
1435 	spin_lock_init(&log->l_icloglock);
1436 	init_waitqueue_head(&log->l_flush_wait);
1437 
1438 	iclogp = &log->l_iclog;
1439 	ASSERT(log->l_iclog_size >= 4096);
1440 	for (i = 0; i < log->l_iclog_bufs; i++) {
1441 		size_t bvec_size = howmany(log->l_iclog_size, PAGE_SIZE) *
1442 				sizeof(struct bio_vec);
1443 
1444 		iclog = kzalloc(sizeof(*iclog) + bvec_size,
1445 				GFP_KERNEL | __GFP_RETRY_MAYFAIL);
1446 		if (!iclog)
1447 			goto out_free_iclog;
1448 
1449 		*iclogp = iclog;
1450 		iclog->ic_prev = prev_iclog;
1451 		prev_iclog = iclog;
1452 
1453 		iclog->ic_header = kvzalloc(log->l_iclog_size,
1454 				GFP_KERNEL | __GFP_RETRY_MAYFAIL);
1455 		if (!iclog->ic_header)
1456 			goto out_free_iclog;
1457 		iclog->ic_header->h_magicno =
1458 			cpu_to_be32(XLOG_HEADER_MAGIC_NUM);
1459 		iclog->ic_header->h_version = cpu_to_be32(
1460 			xfs_has_logv2(log->l_mp) ? 2 : 1);
1461 		iclog->ic_header->h_size = cpu_to_be32(log->l_iclog_size);
1462 		iclog->ic_header->h_fmt = cpu_to_be32(XLOG_FMT);
1463 		memcpy(&iclog->ic_header->h_fs_uuid, &mp->m_sb.sb_uuid,
1464 			sizeof(iclog->ic_header->h_fs_uuid));
1465 
1466 		iclog->ic_datap = (void *)iclog->ic_header + log->l_iclog_hsize;
1467 		iclog->ic_size = log->l_iclog_size - log->l_iclog_hsize;
1468 		iclog->ic_state = XLOG_STATE_ACTIVE;
1469 		iclog->ic_log = log;
1470 		atomic_set(&iclog->ic_refcnt, 0);
1471 		INIT_LIST_HEAD(&iclog->ic_callbacks);
1472 
1473 		init_waitqueue_head(&iclog->ic_force_wait);
1474 		init_waitqueue_head(&iclog->ic_write_wait);
1475 		INIT_WORK(&iclog->ic_end_io_work, xlog_ioend_work);
1476 		sema_init(&iclog->ic_sema, 1);
1477 
1478 		iclogp = &iclog->ic_next;
1479 	}
1480 	*iclogp = log->l_iclog;			/* complete ring */
1481 	log->l_iclog->ic_prev = prev_iclog;	/* re-write 1st prev ptr */
1482 
1483 	log->l_ioend_workqueue = alloc_workqueue("xfs-log/%s",
1484 			XFS_WQFLAGS(WQ_FREEZABLE | WQ_MEM_RECLAIM | WQ_HIGHPRI | WQ_PERCPU),
1485 			0, mp->m_super->s_id);
1486 	if (!log->l_ioend_workqueue)
1487 		goto out_free_iclog;
1488 
1489 	error = xlog_cil_init(log);
1490 	if (error)
1491 		goto out_destroy_workqueue;
1492 	return log;
1493 
1494 out_destroy_workqueue:
1495 	destroy_workqueue(log->l_ioend_workqueue);
1496 out_free_iclog:
1497 	for (iclog = log->l_iclog; iclog; iclog = prev_iclog) {
1498 		prev_iclog = iclog->ic_next;
1499 		kvfree(iclog->ic_header);
1500 		kfree(iclog);
1501 		if (prev_iclog == log->l_iclog)
1502 			break;
1503 	}
1504 out_free_log:
1505 	kfree(log);
1506 out:
1507 	return ERR_PTR(error);
1508 }	/* xlog_alloc_log */
1509 
1510 /*
1511  * Stamp cycle number in every block
1512  */
1513 STATIC void
1514 xlog_pack_data(
1515 	struct xlog		*log,
1516 	struct xlog_in_core	*iclog,
1517 	int			roundoff)
1518 {
1519 	struct xlog_rec_header	*rhead = iclog->ic_header;
1520 	__be32			cycle_lsn = CYCLE_LSN_DISK(rhead->h_lsn);
1521 	char			*dp = iclog->ic_datap;
1522 	int			i;
1523 
1524 	for (i = 0; i < BTOBB(iclog->ic_offset + roundoff); i++) {
1525 		*xlog_cycle_data(rhead, i) = *(__be32 *)dp;
1526 		*(__be32 *)dp = cycle_lsn;
1527 		dp += BBSIZE;
1528 	}
1529 
1530 	for (i = 0; i < (log->l_iclog_hsize >> BBSHIFT) - 1; i++)
1531 		rhead->h_ext[i].xh_cycle = cycle_lsn;
1532 }
1533 
1534 /*
1535  * Calculate the checksum for a log buffer.
1536  *
1537  * This is a little more complicated than it should be because the various
1538  * headers and the actual data are non-contiguous.
1539  */
1540 __le32
1541 xlog_cksum(
1542 	struct xlog		*log,
1543 	struct xlog_rec_header	*rhead,
1544 	char			*dp,
1545 	unsigned int		hdrsize,
1546 	unsigned int		size)
1547 {
1548 	uint32_t		crc;
1549 
1550 	/* first generate the crc for the record header ... */
1551 	crc = xfs_start_cksum_update((char *)rhead, hdrsize,
1552 			      offsetof(struct xlog_rec_header, h_crc));
1553 
1554 	/* ... then for additional cycle data for v2 logs ... */
1555 	if (xfs_has_logv2(log->l_mp)) {
1556 		int		xheads, i;
1557 
1558 		xheads = DIV_ROUND_UP(size, XLOG_HEADER_CYCLE_SIZE) - 1;
1559 		for (i = 0; i < xheads; i++)
1560 			crc = crc32c(crc, &rhead->h_ext[i], XLOG_REC_EXT_SIZE);
1561 	}
1562 
1563 	/* ... and finally for the payload */
1564 	crc = crc32c(crc, dp, size);
1565 
1566 	return xfs_end_cksum(crc);
1567 }
1568 
1569 static void
1570 xlog_bio_end_io(
1571 	struct bio		*bio)
1572 {
1573 	struct xlog_in_core	*iclog = bio->bi_private;
1574 
1575 	queue_work(iclog->ic_log->l_ioend_workqueue,
1576 		   &iclog->ic_end_io_work);
1577 }
1578 
1579 STATIC void
1580 xlog_write_iclog(
1581 	struct xlog		*log,
1582 	struct xlog_in_core	*iclog,
1583 	uint64_t		bno,
1584 	unsigned int		count)
1585 {
1586 	ASSERT(bno < log->l_logBBsize);
1587 	trace_xlog_iclog_write(iclog, _RET_IP_);
1588 
1589 	/*
1590 	 * We lock the iclogbufs here so that we can serialise against I/O
1591 	 * completion during unmount.  We might be processing a shutdown
1592 	 * triggered during unmount, and that can occur asynchronously to the
1593 	 * unmount thread, and hence we need to ensure that completes before
1594 	 * tearing down the iclogbufs.  Hence we need to hold the buffer lock
1595 	 * across the log IO to archieve that.
1596 	 */
1597 	down(&iclog->ic_sema);
1598 	if (xlog_is_shutdown(log)) {
1599 		/*
1600 		 * It would seem logical to return EIO here, but we rely on
1601 		 * the log state machine to propagate I/O errors instead of
1602 		 * doing it here.  We kick of the state machine and unlock
1603 		 * the buffer manually, the code needs to be kept in sync
1604 		 * with the I/O completion path.
1605 		 */
1606 		goto sync;
1607 	}
1608 
1609 	/*
1610 	 * We use REQ_SYNC | REQ_IDLE here to tell the block layer the are more
1611 	 * IOs coming immediately after this one. This prevents the block layer
1612 	 * writeback throttle from throttling log writes behind background
1613 	 * metadata writeback and causing priority inversions.
1614 	 */
1615 	bio_init(&iclog->ic_bio, log->l_targ->bt_bdev, iclog->ic_bvec,
1616 		 howmany(count, PAGE_SIZE),
1617 		 REQ_OP_WRITE | REQ_META | REQ_SYNC | REQ_IDLE);
1618 	iclog->ic_bio.bi_iter.bi_sector = log->l_logBBstart + bno;
1619 	iclog->ic_bio.bi_end_io = xlog_bio_end_io;
1620 	iclog->ic_bio.bi_private = iclog;
1621 
1622 	if (iclog->ic_flags & XLOG_ICL_NEED_FLUSH) {
1623 		iclog->ic_bio.bi_opf |= REQ_PREFLUSH;
1624 		/*
1625 		 * For external log devices, we also need to flush the data
1626 		 * device cache first to ensure all metadata writeback covered
1627 		 * by the LSN in this iclog is on stable storage. This is slow,
1628 		 * but it *must* complete before we issue the external log IO.
1629 		 *
1630 		 * If the flush fails, we cannot conclude that past metadata
1631 		 * writeback from the log succeeded.  Repeating the flush is
1632 		 * not possible, hence we must shut down with log IO error to
1633 		 * avoid shutdown re-entering this path and erroring out again.
1634 		 */
1635 		if (log->l_targ != log->l_mp->m_ddev_targp &&
1636 		    blkdev_issue_flush(log->l_mp->m_ddev_targp->bt_bdev))
1637 			goto shutdown;
1638 	}
1639 	if (iclog->ic_flags & XLOG_ICL_NEED_FUA)
1640 		iclog->ic_bio.bi_opf |= REQ_FUA;
1641 
1642 	iclog->ic_flags &= ~(XLOG_ICL_NEED_FLUSH | XLOG_ICL_NEED_FUA);
1643 
1644 	if (is_vmalloc_addr(iclog->ic_header)) {
1645 		if (!bio_add_vmalloc(&iclog->ic_bio, iclog->ic_header, count))
1646 			goto shutdown;
1647 	} else {
1648 		bio_add_virt_nofail(&iclog->ic_bio, iclog->ic_header, count);
1649 	}
1650 
1651 	/*
1652 	 * If this log buffer would straddle the end of the log we will have
1653 	 * to split it up into two bios, so that we can continue at the start.
1654 	 */
1655 	if (bno + BTOBB(count) > log->l_logBBsize) {
1656 		struct bio *split;
1657 
1658 		split = bio_split(&iclog->ic_bio, log->l_logBBsize - bno,
1659 				  GFP_NOIO, &fs_bio_set);
1660 		bio_chain(split, &iclog->ic_bio);
1661 		submit_bio(split);
1662 
1663 		/* restart at logical offset zero for the remainder */
1664 		iclog->ic_bio.bi_iter.bi_sector = log->l_logBBstart;
1665 	}
1666 
1667 	submit_bio(&iclog->ic_bio);
1668 	return;
1669 shutdown:
1670 	xlog_force_shutdown(log, SHUTDOWN_LOG_IO_ERROR);
1671 sync:
1672 	xlog_state_done_syncing(iclog);
1673 	up(&iclog->ic_sema);
1674 }
1675 
1676 /*
1677  * We need to bump cycle number for the part of the iclog that is
1678  * written to the start of the log. Watch out for the header magic
1679  * number case, though.
1680  */
1681 static void
1682 xlog_split_iclog(
1683 	struct xlog		*log,
1684 	void			*data,
1685 	uint64_t		bno,
1686 	unsigned int		count)
1687 {
1688 	unsigned int		split_offset = BBTOB(log->l_logBBsize - bno);
1689 	unsigned int		i;
1690 
1691 	for (i = split_offset; i < count; i += BBSIZE) {
1692 		uint32_t cycle = get_unaligned_be32(data + i);
1693 
1694 		if (++cycle == XLOG_HEADER_MAGIC_NUM)
1695 			cycle++;
1696 		put_unaligned_be32(cycle, data + i);
1697 	}
1698 }
1699 
1700 static int
1701 xlog_calc_iclog_size(
1702 	struct xlog		*log,
1703 	struct xlog_in_core	*iclog,
1704 	uint32_t		*roundoff)
1705 {
1706 	uint32_t		count_init, count;
1707 
1708 	/* Add for LR header */
1709 	count_init = log->l_iclog_hsize + iclog->ic_offset;
1710 	count = roundup(count_init, log->l_iclog_roundoff);
1711 
1712 	*roundoff = count - count_init;
1713 
1714 	ASSERT(count >= count_init);
1715 	ASSERT(*roundoff < log->l_iclog_roundoff);
1716 	return count;
1717 }
1718 
1719 /*
1720  * Flush out the in-core log (iclog) to the on-disk log in an asynchronous
1721  * fashion.  Previously, we should have moved the current iclog
1722  * ptr in the log to point to the next available iclog.  This allows further
1723  * write to continue while this code syncs out an iclog ready to go.
1724  * Before an in-core log can be written out, the data section must be scanned
1725  * to save away the 1st word of each BBSIZE block into the header.  We replace
1726  * it with the current cycle count.  Each BBSIZE block is tagged with the
1727  * cycle count because there in an implicit assumption that drives will
1728  * guarantee that entire 512 byte blocks get written at once.  In other words,
1729  * we can't have part of a 512 byte block written and part not written.  By
1730  * tagging each block, we will know which blocks are valid when recovering
1731  * after an unclean shutdown.
1732  *
1733  * This routine is single threaded on the iclog.  No other thread can be in
1734  * this routine with the same iclog.  Changing contents of iclog can there-
1735  * fore be done without grabbing the state machine lock.  Updating the global
1736  * log will require grabbing the lock though.
1737  *
1738  * The entire log manager uses a logical block numbering scheme.  Only
1739  * xlog_write_iclog knows about the fact that the log may not start with
1740  * block zero on a given device.
1741  */
1742 STATIC void
1743 xlog_sync(
1744 	struct xlog		*log,
1745 	struct xlog_in_core	*iclog,
1746 	struct xlog_ticket	*ticket)
1747 {
1748 	unsigned int		count;		/* byte count of bwrite */
1749 	unsigned int		roundoff;       /* roundoff to BB or stripe */
1750 	uint64_t		bno;
1751 	unsigned int		size;
1752 
1753 	ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
1754 	trace_xlog_iclog_sync(iclog, _RET_IP_);
1755 
1756 	count = xlog_calc_iclog_size(log, iclog, &roundoff);
1757 
1758 	/*
1759 	 * If we have a ticket, account for the roundoff via the ticket
1760 	 * reservation to avoid touching the hot grant heads needlessly.
1761 	 * Otherwise, we have to move grant heads directly.
1762 	 */
1763 	if (ticket) {
1764 		ticket->t_curr_res -= roundoff;
1765 	} else {
1766 		xlog_grant_add_space(&log->l_reserve_head, roundoff);
1767 		xlog_grant_add_space(&log->l_write_head, roundoff);
1768 	}
1769 
1770 	/* put cycle number in every block */
1771 	xlog_pack_data(log, iclog, roundoff);
1772 
1773 	/* real byte length */
1774 	size = iclog->ic_offset;
1775 	if (xfs_has_logv2(log->l_mp))
1776 		size += roundoff;
1777 	iclog->ic_header->h_len = cpu_to_be32(size);
1778 
1779 	XFS_STATS_INC(log->l_mp, xs_log_writes);
1780 	XFS_STATS_ADD(log->l_mp, xs_log_blocks, BTOBB(count));
1781 
1782 	bno = BLOCK_LSN(be64_to_cpu(iclog->ic_header->h_lsn));
1783 
1784 	/* Do we need to split this write into 2 parts? */
1785 	if (bno + BTOBB(count) > log->l_logBBsize)
1786 		xlog_split_iclog(log, iclog->ic_header, bno, count);
1787 
1788 	/* calculcate the checksum */
1789 	iclog->ic_header->h_crc = xlog_cksum(log, iclog->ic_header,
1790 			iclog->ic_datap, XLOG_REC_SIZE, size);
1791 	/*
1792 	 * Intentionally corrupt the log record CRC based on the error injection
1793 	 * frequency, if defined. This facilitates testing log recovery in the
1794 	 * event of torn writes. Hence, set the IOABORT state to abort the log
1795 	 * write on I/O completion and shutdown the fs. The subsequent mount
1796 	 * detects the bad CRC and attempts to recover.
1797 	 */
1798 #ifdef DEBUG
1799 	if (XFS_TEST_ERROR(log->l_mp, XFS_ERRTAG_LOG_BAD_CRC)) {
1800 		iclog->ic_header->h_crc &= cpu_to_le32(0xAAAAAAAA);
1801 		iclog->ic_fail_crc = true;
1802 		xfs_warn(log->l_mp,
1803 	"Intentionally corrupted log record at LSN 0x%llx. Shutdown imminent.",
1804 			 be64_to_cpu(iclog->ic_header->h_lsn));
1805 	}
1806 #endif
1807 	xlog_verify_iclog(log, iclog, count);
1808 	xlog_write_iclog(log, iclog, bno, count);
1809 }
1810 
1811 /*
1812  * Deallocate a log structure
1813  */
1814 STATIC void
1815 xlog_dealloc_log(
1816 	struct xlog		*log)
1817 {
1818 	struct xlog_in_core	*iclog, *next_iclog;
1819 	int			i;
1820 
1821 	/*
1822 	 * Destroy the CIL after waiting for iclog IO completion because an
1823 	 * iclog EIO error will try to shut down the log, which accesses the
1824 	 * CIL to wake up the waiters.
1825 	 */
1826 	xlog_cil_destroy(log);
1827 
1828 	iclog = log->l_iclog;
1829 	for (i = 0; i < log->l_iclog_bufs; i++) {
1830 		next_iclog = iclog->ic_next;
1831 		kvfree(iclog->ic_header);
1832 		kfree(iclog);
1833 		iclog = next_iclog;
1834 	}
1835 
1836 	log->l_mp->m_log = NULL;
1837 	destroy_workqueue(log->l_ioend_workqueue);
1838 	kfree(log);
1839 }
1840 
1841 /*
1842  * Update counters atomically now that memcpy is done.
1843  */
1844 static inline void
1845 xlog_state_finish_copy(
1846 	struct xlog		*log,
1847 	struct xlog_in_core	*iclog,
1848 	int			record_cnt,
1849 	int			copy_bytes)
1850 {
1851 	lockdep_assert_held(&log->l_icloglock);
1852 
1853 	be32_add_cpu(&iclog->ic_header->h_num_logops, record_cnt);
1854 	iclog->ic_offset += copy_bytes;
1855 }
1856 
1857 /*
1858  * print out info relating to regions written which consume
1859  * the reservation
1860  */
1861 void
1862 xlog_print_tic_res(
1863 	struct xfs_mount	*mp,
1864 	struct xlog_ticket	*ticket)
1865 {
1866 	xfs_warn(mp, "ticket reservation summary:");
1867 	xfs_warn(mp, "  unit res    = %d bytes", ticket->t_unit_res);
1868 	xfs_warn(mp, "  current res = %d bytes", ticket->t_curr_res);
1869 	xfs_warn(mp, "  original count  = %d", ticket->t_ocnt);
1870 	xfs_warn(mp, "  remaining count = %d", ticket->t_cnt);
1871 }
1872 
1873 /*
1874  * Print a summary of the transaction.
1875  */
1876 void
1877 xlog_print_trans(
1878 	struct xfs_trans	*tp)
1879 {
1880 	struct xfs_mount	*mp = tp->t_mountp;
1881 	struct xfs_log_item	*lip;
1882 
1883 	/* dump core transaction and ticket info */
1884 	xfs_warn(mp, "transaction summary:");
1885 	xfs_warn(mp, "  log res   = %d", tp->t_log_res);
1886 	xfs_warn(mp, "  log count = %d", tp->t_log_count);
1887 	xfs_warn(mp, "  flags     = 0x%x", tp->t_flags);
1888 
1889 	xlog_print_tic_res(mp, tp->t_ticket);
1890 
1891 	/* dump each log item */
1892 	list_for_each_entry(lip, &tp->t_items, li_trans) {
1893 		struct xfs_log_vec	*lv = lip->li_lv;
1894 		struct xfs_log_iovec	*vec;
1895 		int			i;
1896 
1897 		xfs_warn(mp, "log item: ");
1898 		xfs_warn(mp, "  type	= 0x%x", lip->li_type);
1899 		xfs_warn(mp, "  flags	= 0x%lx", lip->li_flags);
1900 		if (!lv)
1901 			continue;
1902 		xfs_warn(mp, "  niovecs	= %d", lv->lv_niovecs);
1903 		xfs_warn(mp, "  alloc_size = %d", lv->lv_alloc_size);
1904 		xfs_warn(mp, "  bytes	= %d", lv->lv_bytes);
1905 		xfs_warn(mp, "  buf used= %d", lv->lv_buf_used);
1906 
1907 		/* dump each iovec for the log item */
1908 		vec = lv->lv_iovecp;
1909 		for (i = 0; i < lv->lv_niovecs; i++) {
1910 			int dumplen = min(vec->i_len, 32);
1911 
1912 			xfs_warn(mp, "  iovec[%d]", i);
1913 			xfs_warn(mp, "    type	= 0x%x", vec->i_type);
1914 			xfs_warn(mp, "    len	= %d", vec->i_len);
1915 			xfs_warn(mp, "    first %d bytes of iovec[%d]:", dumplen, i);
1916 			xfs_hex_dump(vec->i_addr, dumplen);
1917 
1918 			vec++;
1919 		}
1920 	}
1921 }
1922 
1923 static inline void
1924 xlog_write_iovec(
1925 	struct xlog_in_core	*iclog,
1926 	uint32_t		*log_offset,
1927 	void			*data,
1928 	uint32_t		write_len,
1929 	int			*bytes_left,
1930 	uint32_t		*record_cnt,
1931 	uint32_t		*data_cnt)
1932 {
1933 	ASSERT(*log_offset < iclog->ic_log->l_iclog_size);
1934 	ASSERT(*log_offset % sizeof(int32_t) == 0);
1935 	ASSERT(write_len % sizeof(int32_t) == 0);
1936 
1937 	memcpy(iclog->ic_datap + *log_offset, data, write_len);
1938 	*log_offset += write_len;
1939 	*bytes_left -= write_len;
1940 	(*record_cnt)++;
1941 	*data_cnt += write_len;
1942 }
1943 
1944 /*
1945  * Write log vectors into a single iclog which is guaranteed by the caller
1946  * to have enough space to write the entire log vector into.
1947  */
1948 static void
1949 xlog_write_full(
1950 	struct xfs_log_vec	*lv,
1951 	struct xlog_ticket	*ticket,
1952 	struct xlog_in_core	*iclog,
1953 	uint32_t		*log_offset,
1954 	uint32_t		*len,
1955 	uint32_t		*record_cnt,
1956 	uint32_t		*data_cnt)
1957 {
1958 	int			index;
1959 
1960 	ASSERT(*log_offset + *len <= iclog->ic_size ||
1961 		iclog->ic_state == XLOG_STATE_WANT_SYNC);
1962 
1963 	/*
1964 	 * Ordered log vectors have no regions to write so this
1965 	 * loop will naturally skip them.
1966 	 */
1967 	for (index = 0; index < lv->lv_niovecs; index++) {
1968 		struct xfs_log_iovec	*reg = &lv->lv_iovecp[index];
1969 		struct xlog_op_header	*ophdr = reg->i_addr;
1970 
1971 		ophdr->oh_tid = cpu_to_be32(ticket->t_tid);
1972 		xlog_write_iovec(iclog, log_offset, reg->i_addr,
1973 				reg->i_len, len, record_cnt, data_cnt);
1974 	}
1975 }
1976 
1977 static int
1978 xlog_write_get_more_iclog_space(
1979 	struct xlog_ticket	*ticket,
1980 	struct xlog_in_core	**iclogp,
1981 	uint32_t		*log_offset,
1982 	uint32_t		len,
1983 	uint32_t		*record_cnt,
1984 	uint32_t		*data_cnt)
1985 {
1986 	struct xlog_in_core	*iclog = *iclogp;
1987 	struct xlog		*log = iclog->ic_log;
1988 	int			error;
1989 
1990 	spin_lock(&log->l_icloglock);
1991 	ASSERT(iclog->ic_state == XLOG_STATE_WANT_SYNC);
1992 	xlog_state_finish_copy(log, iclog, *record_cnt, *data_cnt);
1993 	error = xlog_state_release_iclog(log, iclog, ticket);
1994 	spin_unlock(&log->l_icloglock);
1995 	if (error)
1996 		return error;
1997 
1998 	error = xlog_state_get_iclog_space(log, len, &iclog, ticket,
1999 					log_offset);
2000 	if (error)
2001 		return error;
2002 	*record_cnt = 0;
2003 	*data_cnt = 0;
2004 	*iclogp = iclog;
2005 	return 0;
2006 }
2007 
2008 /*
2009  * Write log vectors into a single iclog which is smaller than the current chain
2010  * length. We write until we cannot fit a full record into the remaining space
2011  * and then stop. We return the log vector that is to be written that cannot
2012  * wholly fit in the iclog.
2013  */
2014 static int
2015 xlog_write_partial(
2016 	struct xfs_log_vec	*lv,
2017 	struct xlog_ticket	*ticket,
2018 	struct xlog_in_core	**iclogp,
2019 	uint32_t		*log_offset,
2020 	uint32_t		*len,
2021 	uint32_t		*record_cnt,
2022 	uint32_t		*data_cnt)
2023 {
2024 	struct xlog_in_core	*iclog = *iclogp;
2025 	struct xlog_op_header	*ophdr;
2026 	int			index = 0;
2027 	uint32_t		rlen;
2028 	int			error;
2029 
2030 	/* walk the logvec, copying until we run out of space in the iclog */
2031 	for (index = 0; index < lv->lv_niovecs; index++) {
2032 		struct xfs_log_iovec	*reg = &lv->lv_iovecp[index];
2033 		uint32_t		reg_offset = 0;
2034 
2035 		/*
2036 		 * The first region of a continuation must have a non-zero
2037 		 * length otherwise log recovery will just skip over it and
2038 		 * start recovering from the next opheader it finds. Because we
2039 		 * mark the next opheader as a continuation, recovery will then
2040 		 * incorrectly add the continuation to the previous region and
2041 		 * that breaks stuff.
2042 		 *
2043 		 * Hence if there isn't space for region data after the
2044 		 * opheader, then we need to start afresh with a new iclog.
2045 		 */
2046 		if (iclog->ic_size - *log_offset <=
2047 					sizeof(struct xlog_op_header)) {
2048 			error = xlog_write_get_more_iclog_space(ticket,
2049 					&iclog, log_offset, *len, record_cnt,
2050 					data_cnt);
2051 			if (error)
2052 				return error;
2053 		}
2054 
2055 		ophdr = reg->i_addr;
2056 		rlen = min_t(uint32_t, reg->i_len, iclog->ic_size - *log_offset);
2057 
2058 		ophdr->oh_tid = cpu_to_be32(ticket->t_tid);
2059 		ophdr->oh_len = cpu_to_be32(rlen - sizeof(struct xlog_op_header));
2060 		if (rlen != reg->i_len)
2061 			ophdr->oh_flags |= XLOG_CONTINUE_TRANS;
2062 
2063 		xlog_write_iovec(iclog, log_offset, reg->i_addr,
2064 				rlen, len, record_cnt, data_cnt);
2065 
2066 		/* If we wrote the whole region, move to the next. */
2067 		if (rlen == reg->i_len)
2068 			continue;
2069 
2070 		/*
2071 		 * We now have a partially written iovec, but it can span
2072 		 * multiple iclogs so we loop here. First we release the iclog
2073 		 * we currently have, then we get a new iclog and add a new
2074 		 * opheader. Then we continue copying from where we were until
2075 		 * we either complete the iovec or fill the iclog. If we
2076 		 * complete the iovec, then we increment the index and go right
2077 		 * back to the top of the outer loop. if we fill the iclog, we
2078 		 * run the inner loop again.
2079 		 *
2080 		 * This is complicated by the tail of a region using all the
2081 		 * space in an iclog and hence requiring us to release the iclog
2082 		 * and get a new one before returning to the outer loop. We must
2083 		 * always guarantee that we exit this inner loop with at least
2084 		 * space for log transaction opheaders left in the current
2085 		 * iclog, hence we cannot just terminate the loop at the end
2086 		 * of the of the continuation. So we loop while there is no
2087 		 * space left in the current iclog, and check for the end of the
2088 		 * continuation after getting a new iclog.
2089 		 */
2090 		do {
2091 			/*
2092 			 * Ensure we include the continuation opheader in the
2093 			 * space we need in the new iclog by adding that size
2094 			 * to the length we require. This continuation opheader
2095 			 * needs to be accounted to the ticket as the space it
2096 			 * consumes hasn't been accounted to the lv we are
2097 			 * writing.
2098 			 */
2099 			error = xlog_write_get_more_iclog_space(ticket,
2100 					&iclog, log_offset,
2101 					*len + sizeof(struct xlog_op_header),
2102 					record_cnt, data_cnt);
2103 			if (error)
2104 				return error;
2105 
2106 			ophdr = iclog->ic_datap + *log_offset;
2107 			ophdr->oh_tid = cpu_to_be32(ticket->t_tid);
2108 			ophdr->oh_clientid = XFS_TRANSACTION;
2109 			ophdr->oh_res2 = 0;
2110 			ophdr->oh_flags = XLOG_WAS_CONT_TRANS;
2111 
2112 			ticket->t_curr_res -= sizeof(struct xlog_op_header);
2113 			*log_offset += sizeof(struct xlog_op_header);
2114 			*data_cnt += sizeof(struct xlog_op_header);
2115 
2116 			/*
2117 			 * If rlen fits in the iclog, then end the region
2118 			 * continuation. Otherwise we're going around again.
2119 			 */
2120 			reg_offset += rlen;
2121 			rlen = reg->i_len - reg_offset;
2122 			if (rlen <= iclog->ic_size - *log_offset)
2123 				ophdr->oh_flags |= XLOG_END_TRANS;
2124 			else
2125 				ophdr->oh_flags |= XLOG_CONTINUE_TRANS;
2126 
2127 			rlen = min_t(uint32_t, rlen, iclog->ic_size - *log_offset);
2128 			ophdr->oh_len = cpu_to_be32(rlen);
2129 
2130 			xlog_write_iovec(iclog, log_offset,
2131 					reg->i_addr + reg_offset,
2132 					rlen, len, record_cnt, data_cnt);
2133 
2134 		} while (ophdr->oh_flags & XLOG_CONTINUE_TRANS);
2135 	}
2136 
2137 	/*
2138 	 * No more iovecs remain in this logvec so return the next log vec to
2139 	 * the caller so it can go back to fast path copying.
2140 	 */
2141 	*iclogp = iclog;
2142 	return 0;
2143 }
2144 
2145 /*
2146  * Write some region out to in-core log
2147  *
2148  * This will be called when writing externally provided regions or when
2149  * writing out a commit record for a given transaction.
2150  *
2151  * General algorithm:
2152  *	1. Find total length of this write.  This may include adding to the
2153  *		lengths passed in.
2154  *	2. Check whether we violate the tickets reservation.
2155  *	3. While writing to this iclog
2156  *	    A. Reserve as much space in this iclog as can get
2157  *	    B. If this is first write, save away start lsn
2158  *	    C. While writing this region:
2159  *		1. If first write of transaction, write start record
2160  *		2. Write log operation header (header per region)
2161  *		3. Find out if we can fit entire region into this iclog
2162  *		4. Potentially, verify destination memcpy ptr
2163  *		5. Memcpy (partial) region
2164  *		6. If partial copy, release iclog; otherwise, continue
2165  *			copying more regions into current iclog
2166  *	4. Mark want sync bit (in simulation mode)
2167  *	5. Release iclog for potential flush to on-disk log.
2168  *
2169  * ERRORS:
2170  * 1.	Panic if reservation is overrun.  This should never happen since
2171  *	reservation amounts are generated internal to the filesystem.
2172  * NOTES:
2173  * 1. Tickets are single threaded data structures.
2174  * 2. The XLOG_END_TRANS & XLOG_CONTINUE_TRANS flags are passed down to the
2175  *	syncing routine.  When a single log_write region needs to span
2176  *	multiple in-core logs, the XLOG_CONTINUE_TRANS bit should be set
2177  *	on all log operation writes which don't contain the end of the
2178  *	region.  The XLOG_END_TRANS bit is used for the in-core log
2179  *	operation which contains the end of the continued log_write region.
2180  * 3. When xlog_state_get_iclog_space() grabs the rest of the current iclog,
2181  *	we don't really know exactly how much space will be used.  As a result,
2182  *	we don't update ic_offset until the end when we know exactly how many
2183  *	bytes have been written out.
2184  */
2185 int
2186 xlog_write(
2187 	struct xlog		*log,
2188 	struct xfs_cil_ctx	*ctx,
2189 	struct list_head	*lv_chain,
2190 	struct xlog_ticket	*ticket,
2191 	uint32_t		len)
2192 
2193 {
2194 	struct xlog_in_core	*iclog = NULL;
2195 	struct xfs_log_vec	*lv;
2196 	uint32_t		record_cnt = 0;
2197 	uint32_t		data_cnt = 0;
2198 	int			error = 0;
2199 	int			log_offset;
2200 
2201 	if (ticket->t_curr_res < 0) {
2202 		xfs_alert_tag(log->l_mp, XFS_PTAG_LOGRES,
2203 		     "ctx ticket reservation ran out. Need to up reservation");
2204 		xlog_print_tic_res(log->l_mp, ticket);
2205 		xlog_force_shutdown(log, SHUTDOWN_LOG_IO_ERROR);
2206 	}
2207 
2208 	error = xlog_state_get_iclog_space(log, len, &iclog, ticket,
2209 					   &log_offset);
2210 	if (error)
2211 		return error;
2212 
2213 	ASSERT(log_offset <= iclog->ic_size - 1);
2214 
2215 	/*
2216 	 * If we have a context pointer, pass it the first iclog we are
2217 	 * writing to so it can record state needed for iclog write
2218 	 * ordering.
2219 	 */
2220 	if (ctx)
2221 		xlog_cil_set_ctx_write_state(ctx, iclog);
2222 
2223 	list_for_each_entry(lv, lv_chain, lv_list) {
2224 		/*
2225 		 * If the entire log vec does not fit in the iclog, punt it to
2226 		 * the partial copy loop which can handle this case.
2227 		 */
2228 		if (lv->lv_niovecs &&
2229 		    lv->lv_bytes > iclog->ic_size - log_offset) {
2230 			error = xlog_write_partial(lv, ticket, &iclog,
2231 					&log_offset, &len, &record_cnt,
2232 					&data_cnt);
2233 			if (error) {
2234 				/*
2235 				 * We have no iclog to release, so just return
2236 				 * the error immediately.
2237 				 */
2238 				return error;
2239 			}
2240 		} else {
2241 			xlog_write_full(lv, ticket, iclog, &log_offset,
2242 					 &len, &record_cnt, &data_cnt);
2243 		}
2244 	}
2245 	ASSERT(len == 0);
2246 
2247 	/*
2248 	 * We've already been guaranteed that the last writes will fit inside
2249 	 * the current iclog, and hence it will already have the space used by
2250 	 * those writes accounted to it. Hence we do not need to update the
2251 	 * iclog with the number of bytes written here.
2252 	 */
2253 	spin_lock(&log->l_icloglock);
2254 	xlog_state_finish_copy(log, iclog, record_cnt, 0);
2255 	error = xlog_state_release_iclog(log, iclog, ticket);
2256 	spin_unlock(&log->l_icloglock);
2257 
2258 	return error;
2259 }
2260 
2261 static void
2262 xlog_state_activate_iclog(
2263 	struct xlog_in_core	*iclog,
2264 	int			*iclogs_changed)
2265 {
2266 	ASSERT(list_empty_careful(&iclog->ic_callbacks));
2267 	trace_xlog_iclog_activate(iclog, _RET_IP_);
2268 
2269 	/*
2270 	 * If the number of ops in this iclog indicate it just contains the
2271 	 * dummy transaction, we can change state into IDLE (the second time
2272 	 * around). Otherwise we should change the state into NEED a dummy.
2273 	 * We don't need to cover the dummy.
2274 	 */
2275 	if (*iclogs_changed == 0 &&
2276 	    iclog->ic_header->h_num_logops == cpu_to_be32(XLOG_COVER_OPS)) {
2277 		*iclogs_changed = 1;
2278 	} else {
2279 		/*
2280 		 * We have two dirty iclogs so start over.  This could also be
2281 		 * num of ops indicating this is not the dummy going out.
2282 		 */
2283 		*iclogs_changed = 2;
2284 	}
2285 
2286 	iclog->ic_state	= XLOG_STATE_ACTIVE;
2287 	iclog->ic_offset = 0;
2288 	iclog->ic_header->h_num_logops = 0;
2289 	memset(iclog->ic_header->h_cycle_data, 0,
2290 		sizeof(iclog->ic_header->h_cycle_data));
2291 	iclog->ic_header->h_lsn = 0;
2292 	iclog->ic_header->h_tail_lsn = 0;
2293 }
2294 
2295 /*
2296  * Loop through all iclogs and mark all iclogs currently marked DIRTY as
2297  * ACTIVE after iclog I/O has completed.
2298  */
2299 static void
2300 xlog_state_activate_iclogs(
2301 	struct xlog		*log,
2302 	int			*iclogs_changed)
2303 {
2304 	struct xlog_in_core	*iclog = log->l_iclog;
2305 
2306 	do {
2307 		if (iclog->ic_state == XLOG_STATE_DIRTY)
2308 			xlog_state_activate_iclog(iclog, iclogs_changed);
2309 		/*
2310 		 * The ordering of marking iclogs ACTIVE must be maintained, so
2311 		 * an iclog doesn't become ACTIVE beyond one that is SYNCING.
2312 		 */
2313 		else if (iclog->ic_state != XLOG_STATE_ACTIVE)
2314 			break;
2315 	} while ((iclog = iclog->ic_next) != log->l_iclog);
2316 }
2317 
2318 static int
2319 xlog_covered_state(
2320 	int			prev_state,
2321 	int			iclogs_changed)
2322 {
2323 	/*
2324 	 * We go to NEED for any non-covering writes. We go to NEED2 if we just
2325 	 * wrote the first covering record (DONE). We go to IDLE if we just
2326 	 * wrote the second covering record (DONE2) and remain in IDLE until a
2327 	 * non-covering write occurs.
2328 	 */
2329 	switch (prev_state) {
2330 	case XLOG_STATE_COVER_IDLE:
2331 		if (iclogs_changed == 1)
2332 			return XLOG_STATE_COVER_IDLE;
2333 		fallthrough;
2334 	case XLOG_STATE_COVER_NEED:
2335 	case XLOG_STATE_COVER_NEED2:
2336 		break;
2337 	case XLOG_STATE_COVER_DONE:
2338 		if (iclogs_changed == 1)
2339 			return XLOG_STATE_COVER_NEED2;
2340 		break;
2341 	case XLOG_STATE_COVER_DONE2:
2342 		if (iclogs_changed == 1)
2343 			return XLOG_STATE_COVER_IDLE;
2344 		break;
2345 	default:
2346 		ASSERT(0);
2347 	}
2348 
2349 	return XLOG_STATE_COVER_NEED;
2350 }
2351 
2352 STATIC void
2353 xlog_state_clean_iclog(
2354 	struct xlog		*log,
2355 	struct xlog_in_core	*dirty_iclog)
2356 {
2357 	int			iclogs_changed = 0;
2358 
2359 	trace_xlog_iclog_clean(dirty_iclog, _RET_IP_);
2360 
2361 	dirty_iclog->ic_state = XLOG_STATE_DIRTY;
2362 
2363 	xlog_state_activate_iclogs(log, &iclogs_changed);
2364 	wake_up_all(&dirty_iclog->ic_force_wait);
2365 
2366 	if (iclogs_changed) {
2367 		log->l_covered_state = xlog_covered_state(log->l_covered_state,
2368 				iclogs_changed);
2369 	}
2370 }
2371 
2372 STATIC xfs_lsn_t
2373 xlog_get_lowest_lsn(
2374 	struct xlog		*log)
2375 {
2376 	struct xlog_in_core	*iclog = log->l_iclog;
2377 	xfs_lsn_t		lowest_lsn = 0, lsn;
2378 
2379 	do {
2380 		if (iclog->ic_state == XLOG_STATE_ACTIVE ||
2381 		    iclog->ic_state == XLOG_STATE_DIRTY)
2382 			continue;
2383 
2384 		lsn = be64_to_cpu(iclog->ic_header->h_lsn);
2385 		if ((lsn && !lowest_lsn) || XFS_LSN_CMP(lsn, lowest_lsn) < 0)
2386 			lowest_lsn = lsn;
2387 	} while ((iclog = iclog->ic_next) != log->l_iclog);
2388 
2389 	return lowest_lsn;
2390 }
2391 
2392 /*
2393  * Return true if we need to stop processing, false to continue to the next
2394  * iclog. The caller will need to run callbacks if the iclog is returned in the
2395  * XLOG_STATE_CALLBACK state.
2396  */
2397 static bool
2398 xlog_state_iodone_process_iclog(
2399 	struct xlog		*log,
2400 	struct xlog_in_core	*iclog)
2401 {
2402 	xfs_lsn_t		lowest_lsn;
2403 	xfs_lsn_t		header_lsn;
2404 
2405 	switch (iclog->ic_state) {
2406 	case XLOG_STATE_ACTIVE:
2407 	case XLOG_STATE_DIRTY:
2408 		/*
2409 		 * Skip all iclogs in the ACTIVE & DIRTY states:
2410 		 */
2411 		return false;
2412 	case XLOG_STATE_DONE_SYNC:
2413 		/*
2414 		 * Now that we have an iclog that is in the DONE_SYNC state, do
2415 		 * one more check here to see if we have chased our tail around.
2416 		 * If this is not the lowest lsn iclog, then we will leave it
2417 		 * for another completion to process.
2418 		 */
2419 		header_lsn = be64_to_cpu(iclog->ic_header->h_lsn);
2420 		lowest_lsn = xlog_get_lowest_lsn(log);
2421 		if (lowest_lsn && XFS_LSN_CMP(lowest_lsn, header_lsn) < 0)
2422 			return false;
2423 		/*
2424 		 * If there are no callbacks on this iclog, we can mark it clean
2425 		 * immediately and return. Otherwise we need to run the
2426 		 * callbacks.
2427 		 */
2428 		if (list_empty(&iclog->ic_callbacks)) {
2429 			xlog_state_clean_iclog(log, iclog);
2430 			return false;
2431 		}
2432 		trace_xlog_iclog_callback(iclog, _RET_IP_);
2433 		iclog->ic_state = XLOG_STATE_CALLBACK;
2434 		return false;
2435 	default:
2436 		/*
2437 		 * Can only perform callbacks in order.  Since this iclog is not
2438 		 * in the DONE_SYNC state, we skip the rest and just try to
2439 		 * clean up.
2440 		 */
2441 		return true;
2442 	}
2443 }
2444 
2445 /*
2446  * Loop over all the iclogs, running attached callbacks on them. Return true if
2447  * we ran any callbacks, indicating that we dropped the icloglock. We don't need
2448  * to handle transient shutdown state here at all because
2449  * xlog_state_shutdown_callbacks() will be run to do the necessary shutdown
2450  * cleanup of the callbacks.
2451  */
2452 static bool
2453 xlog_state_do_iclog_callbacks(
2454 	struct xlog		*log)
2455 		__releases(&log->l_icloglock)
2456 		__acquires(&log->l_icloglock)
2457 {
2458 	struct xlog_in_core	*first_iclog = log->l_iclog;
2459 	struct xlog_in_core	*iclog = first_iclog;
2460 	bool			ran_callback = false;
2461 
2462 	do {
2463 		LIST_HEAD(cb_list);
2464 
2465 		if (xlog_state_iodone_process_iclog(log, iclog))
2466 			break;
2467 		if (iclog->ic_state != XLOG_STATE_CALLBACK) {
2468 			iclog = iclog->ic_next;
2469 			continue;
2470 		}
2471 		list_splice_init(&iclog->ic_callbacks, &cb_list);
2472 		spin_unlock(&log->l_icloglock);
2473 
2474 		trace_xlog_iclog_callbacks_start(iclog, _RET_IP_);
2475 		xlog_cil_process_committed(&cb_list);
2476 		trace_xlog_iclog_callbacks_done(iclog, _RET_IP_);
2477 		ran_callback = true;
2478 
2479 		spin_lock(&log->l_icloglock);
2480 		xlog_state_clean_iclog(log, iclog);
2481 		iclog = iclog->ic_next;
2482 	} while (iclog != first_iclog);
2483 
2484 	return ran_callback;
2485 }
2486 
2487 
2488 /*
2489  * Loop running iclog completion callbacks until there are no more iclogs in a
2490  * state that can run callbacks.
2491  */
2492 STATIC void
2493 xlog_state_do_callback(
2494 	struct xlog		*log)
2495 {
2496 	int			flushcnt = 0;
2497 	int			repeats = 0;
2498 
2499 	spin_lock(&log->l_icloglock);
2500 	while (xlog_state_do_iclog_callbacks(log)) {
2501 		if (xlog_is_shutdown(log))
2502 			break;
2503 
2504 		if (++repeats > 5000) {
2505 			flushcnt += repeats;
2506 			repeats = 0;
2507 			xfs_warn(log->l_mp,
2508 				"%s: possible infinite loop (%d iterations)",
2509 				__func__, flushcnt);
2510 		}
2511 	}
2512 
2513 	if (log->l_iclog->ic_state == XLOG_STATE_ACTIVE)
2514 		wake_up_all(&log->l_flush_wait);
2515 
2516 	spin_unlock(&log->l_icloglock);
2517 }
2518 
2519 
2520 /*
2521  * Finish transitioning this iclog to the dirty state.
2522  *
2523  * Callbacks could take time, so they are done outside the scope of the
2524  * global state machine log lock.
2525  */
2526 STATIC void
2527 xlog_state_done_syncing(
2528 	struct xlog_in_core	*iclog)
2529 {
2530 	struct xlog		*log = iclog->ic_log;
2531 
2532 	spin_lock(&log->l_icloglock);
2533 	ASSERT(atomic_read(&iclog->ic_refcnt) == 0);
2534 	trace_xlog_iclog_sync_done(iclog, _RET_IP_);
2535 
2536 	/*
2537 	 * If we got an error, either on the first buffer, or in the case of
2538 	 * split log writes, on the second, we shut down the file system and
2539 	 * no iclogs should ever be attempted to be written to disk again.
2540 	 */
2541 	if (!xlog_is_shutdown(log)) {
2542 		ASSERT(iclog->ic_state == XLOG_STATE_SYNCING);
2543 		iclog->ic_state = XLOG_STATE_DONE_SYNC;
2544 	}
2545 
2546 	/*
2547 	 * Someone could be sleeping prior to writing out the next
2548 	 * iclog buffer, we wake them all, one will get to do the
2549 	 * I/O, the others get to wait for the result.
2550 	 */
2551 	wake_up_all(&iclog->ic_write_wait);
2552 	spin_unlock(&log->l_icloglock);
2553 	xlog_state_do_callback(log);
2554 }
2555 
2556 /*
2557  * If the head of the in-core log ring is not (ACTIVE or DIRTY), then we must
2558  * sleep.  We wait on the flush queue on the head iclog as that should be
2559  * the first iclog to complete flushing. Hence if all iclogs are syncing,
2560  * we will wait here and all new writes will sleep until a sync completes.
2561  *
2562  * The in-core logs are used in a circular fashion. They are not used
2563  * out-of-order even when an iclog past the head is free.
2564  *
2565  * return:
2566  *	* log_offset where xlog_write() can start writing into the in-core
2567  *		log's data space.
2568  *	* in-core log pointer to which xlog_write() should write.
2569  *	* boolean indicating this is a continued write to an in-core log.
2570  *		If this is the last write, then the in-core log's offset field
2571  *		needs to be incremented, depending on the amount of data which
2572  *		is copied.
2573  */
2574 STATIC int
2575 xlog_state_get_iclog_space(
2576 	struct xlog		*log,
2577 	int			len,
2578 	struct xlog_in_core	**iclogp,
2579 	struct xlog_ticket	*ticket,
2580 	int			*logoffsetp)
2581 {
2582 	int			log_offset;
2583 	struct xlog_rec_header	*head;
2584 	struct xlog_in_core	*iclog;
2585 
2586 restart:
2587 	spin_lock(&log->l_icloglock);
2588 	if (xlog_is_shutdown(log)) {
2589 		spin_unlock(&log->l_icloglock);
2590 		return -EIO;
2591 	}
2592 
2593 	iclog = log->l_iclog;
2594 	if (iclog->ic_state != XLOG_STATE_ACTIVE) {
2595 		XFS_STATS_INC(log->l_mp, xs_log_noiclogs);
2596 
2597 		/* Wait for log writes to have flushed */
2598 		xlog_wait(&log->l_flush_wait, &log->l_icloglock);
2599 		goto restart;
2600 	}
2601 
2602 	head = iclog->ic_header;
2603 
2604 	atomic_inc(&iclog->ic_refcnt);	/* prevents sync */
2605 	log_offset = iclog->ic_offset;
2606 
2607 	trace_xlog_iclog_get_space(iclog, _RET_IP_);
2608 
2609 	/* On the 1st write to an iclog, figure out lsn.  This works
2610 	 * if iclogs marked XLOG_STATE_WANT_SYNC always write out what they are
2611 	 * committing to.  If the offset is set, that's how many blocks
2612 	 * must be written.
2613 	 */
2614 	if (log_offset == 0) {
2615 		ticket->t_curr_res -= log->l_iclog_hsize;
2616 		head->h_cycle = cpu_to_be32(log->l_curr_cycle);
2617 		head->h_lsn = cpu_to_be64(
2618 			xlog_assign_lsn(log->l_curr_cycle, log->l_curr_block));
2619 		ASSERT(log->l_curr_block >= 0);
2620 	}
2621 
2622 	/* If there is enough room to write everything, then do it.  Otherwise,
2623 	 * claim the rest of the region and make sure the XLOG_STATE_WANT_SYNC
2624 	 * bit is on, so this will get flushed out.  Don't update ic_offset
2625 	 * until you know exactly how many bytes get copied.  Therefore, wait
2626 	 * until later to update ic_offset.
2627 	 *
2628 	 * xlog_write() algorithm assumes that at least 2 xlog_op_header's
2629 	 * can fit into remaining data section.
2630 	 */
2631 	if (iclog->ic_size - iclog->ic_offset <
2632 	    2 * sizeof(struct xlog_op_header)) {
2633 		int		error = 0;
2634 
2635 		xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2636 
2637 		/*
2638 		 * If we are the only one writing to this iclog, sync it to
2639 		 * disk.  We need to do an atomic compare and decrement here to
2640 		 * avoid racing with concurrent atomic_dec_and_lock() calls in
2641 		 * xlog_state_release_iclog() when there is more than one
2642 		 * reference to the iclog.
2643 		 */
2644 		if (!atomic_add_unless(&iclog->ic_refcnt, -1, 1))
2645 			error = xlog_state_release_iclog(log, iclog, ticket);
2646 		spin_unlock(&log->l_icloglock);
2647 		if (error)
2648 			return error;
2649 		goto restart;
2650 	}
2651 
2652 	/* Do we have enough room to write the full amount in the remainder
2653 	 * of this iclog?  Or must we continue a write on the next iclog and
2654 	 * mark this iclog as completely taken?  In the case where we switch
2655 	 * iclogs (to mark it taken), this particular iclog will release/sync
2656 	 * to disk in xlog_write().
2657 	 */
2658 	if (len <= iclog->ic_size - iclog->ic_offset)
2659 		iclog->ic_offset += len;
2660 	else
2661 		xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2662 	*iclogp = iclog;
2663 
2664 	ASSERT(iclog->ic_offset <= iclog->ic_size);
2665 	spin_unlock(&log->l_icloglock);
2666 
2667 	*logoffsetp = log_offset;
2668 	return 0;
2669 }
2670 
2671 /*
2672  * The first cnt-1 times a ticket goes through here we don't need to move the
2673  * grant write head because the permanent reservation has reserved cnt times the
2674  * unit amount.  Release part of current permanent unit reservation and reset
2675  * current reservation to be one units worth.  Also move grant reservation head
2676  * forward.
2677  */
2678 void
2679 xfs_log_ticket_regrant(
2680 	struct xlog		*log,
2681 	struct xlog_ticket	*ticket)
2682 {
2683 	trace_xfs_log_ticket_regrant(log, ticket);
2684 
2685 	if (ticket->t_cnt > 0)
2686 		ticket->t_cnt--;
2687 
2688 	xlog_grant_sub_space(&log->l_reserve_head, ticket->t_curr_res);
2689 	xlog_grant_sub_space(&log->l_write_head, ticket->t_curr_res);
2690 	ticket->t_curr_res = ticket->t_unit_res;
2691 
2692 	trace_xfs_log_ticket_regrant_sub(log, ticket);
2693 
2694 	/* just return if we still have some of the pre-reserved space */
2695 	if (!ticket->t_cnt) {
2696 		xlog_grant_add_space(&log->l_reserve_head, ticket->t_unit_res);
2697 		trace_xfs_log_ticket_regrant_exit(log, ticket);
2698 	}
2699 
2700 	xfs_log_ticket_put(ticket);
2701 }
2702 
2703 /*
2704  * Give back the space left from a reservation.
2705  *
2706  * All the information we need to make a correct determination of space left
2707  * is present.  For non-permanent reservations, things are quite easy.  The
2708  * count should have been decremented to zero.  We only need to deal with the
2709  * space remaining in the current reservation part of the ticket.  If the
2710  * ticket contains a permanent reservation, there may be left over space which
2711  * needs to be released.  A count of N means that N-1 refills of the current
2712  * reservation can be done before we need to ask for more space.  The first
2713  * one goes to fill up the first current reservation.  Once we run out of
2714  * space, the count will stay at zero and the only space remaining will be
2715  * in the current reservation field.
2716  */
2717 void
2718 xfs_log_ticket_ungrant(
2719 	struct xlog		*log,
2720 	struct xlog_ticket	*ticket)
2721 {
2722 	int			bytes;
2723 
2724 	trace_xfs_log_ticket_ungrant(log, ticket);
2725 
2726 	if (ticket->t_cnt > 0)
2727 		ticket->t_cnt--;
2728 
2729 	trace_xfs_log_ticket_ungrant_sub(log, ticket);
2730 
2731 	/*
2732 	 * If this is a permanent reservation ticket, we may be able to free
2733 	 * up more space based on the remaining count.
2734 	 */
2735 	bytes = ticket->t_curr_res;
2736 	if (ticket->t_cnt > 0) {
2737 		ASSERT(ticket->t_flags & XLOG_TIC_PERM_RESERV);
2738 		bytes += ticket->t_unit_res*ticket->t_cnt;
2739 	}
2740 
2741 	xlog_grant_sub_space(&log->l_reserve_head, bytes);
2742 	xlog_grant_sub_space(&log->l_write_head, bytes);
2743 
2744 	trace_xfs_log_ticket_ungrant_exit(log, ticket);
2745 
2746 	xfs_log_space_wake(log->l_mp);
2747 	xfs_log_ticket_put(ticket);
2748 }
2749 
2750 /*
2751  * This routine will mark the current iclog in the ring as WANT_SYNC and move
2752  * the current iclog pointer to the next iclog in the ring.
2753  */
2754 void
2755 xlog_state_switch_iclogs(
2756 	struct xlog		*log,
2757 	struct xlog_in_core	*iclog,
2758 	int			eventual_size)
2759 {
2760 	ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
2761 	assert_spin_locked(&log->l_icloglock);
2762 	trace_xlog_iclog_switch(iclog, _RET_IP_);
2763 
2764 	if (!eventual_size)
2765 		eventual_size = iclog->ic_offset;
2766 	iclog->ic_state = XLOG_STATE_WANT_SYNC;
2767 	iclog->ic_header->h_prev_block = cpu_to_be32(log->l_prev_block);
2768 	log->l_prev_block = log->l_curr_block;
2769 	log->l_prev_cycle = log->l_curr_cycle;
2770 
2771 	/* roll log?: ic_offset changed later */
2772 	log->l_curr_block += BTOBB(eventual_size)+BTOBB(log->l_iclog_hsize);
2773 
2774 	/* Round up to next log-sunit */
2775 	if (log->l_iclog_roundoff > BBSIZE) {
2776 		uint32_t sunit_bb = BTOBB(log->l_iclog_roundoff);
2777 		log->l_curr_block = roundup(log->l_curr_block, sunit_bb);
2778 	}
2779 
2780 	if (log->l_curr_block >= log->l_logBBsize) {
2781 		/*
2782 		 * Rewind the current block before the cycle is bumped to make
2783 		 * sure that the combined LSN never transiently moves forward
2784 		 * when the log wraps to the next cycle. This is to support the
2785 		 * unlocked sample of these fields from xlog_valid_lsn(). Most
2786 		 * other cases should acquire l_icloglock.
2787 		 */
2788 		log->l_curr_block -= log->l_logBBsize;
2789 		ASSERT(log->l_curr_block >= 0);
2790 		smp_wmb();
2791 		log->l_curr_cycle++;
2792 		if (log->l_curr_cycle == XLOG_HEADER_MAGIC_NUM)
2793 			log->l_curr_cycle++;
2794 	}
2795 	ASSERT(iclog == log->l_iclog);
2796 	log->l_iclog = iclog->ic_next;
2797 }
2798 
2799 /*
2800  * Force the iclog to disk and check if the iclog has been completed before
2801  * xlog_force_iclog() returns. This can happen on synchronous (e.g.
2802  * pmem) or fast async storage because we drop the icloglock to issue the IO.
2803  * If completion has already occurred, tell the caller so that it can avoid an
2804  * unnecessary wait on the iclog.
2805  */
2806 static int
2807 xlog_force_and_check_iclog(
2808 	struct xlog_in_core	*iclog,
2809 	bool			*completed)
2810 {
2811 	xfs_lsn_t		lsn = be64_to_cpu(iclog->ic_header->h_lsn);
2812 	int			error;
2813 
2814 	*completed = false;
2815 	error = xlog_force_iclog(iclog);
2816 	if (error)
2817 		return error;
2818 
2819 	/*
2820 	 * If the iclog has already been completed and reused the header LSN
2821 	 * will have been rewritten by completion
2822 	 */
2823 	if (be64_to_cpu(iclog->ic_header->h_lsn) != lsn)
2824 		*completed = true;
2825 	return 0;
2826 }
2827 
2828 /*
2829  * Write out all data in the in-core log as of this exact moment in time.
2830  *
2831  * Data may be written to the in-core log during this call.  However,
2832  * we don't guarantee this data will be written out.  A change from past
2833  * implementation means this routine will *not* write out zero length LRs.
2834  *
2835  * Basically, we try and perform an intelligent scan of the in-core logs.
2836  * If we determine there is no flushable data, we just return.  There is no
2837  * flushable data if:
2838  *
2839  *	1. the current iclog is active and has no data; the previous iclog
2840  *		is in the active or dirty state.
2841  *	2. the current iclog is dirty, and the previous iclog is in the
2842  *		active or dirty state.
2843  *
2844  * We may sleep if:
2845  *
2846  *	1. the current iclog is not in the active nor dirty state.
2847  *	2. the current iclog dirty, and the previous iclog is not in the
2848  *		active nor dirty state.
2849  *	3. the current iclog is active, and there is another thread writing
2850  *		to this particular iclog.
2851  *	4. a) the current iclog is active and has no other writers
2852  *	   b) when we return from flushing out this iclog, it is still
2853  *		not in the active nor dirty state.
2854  */
2855 int
2856 xfs_log_force(
2857 	struct xfs_mount	*mp,
2858 	uint			flags)
2859 {
2860 	struct xlog		*log = mp->m_log;
2861 	struct xlog_in_core	*iclog;
2862 
2863 	XFS_STATS_INC(mp, xs_log_force);
2864 	trace_xfs_log_force(mp, 0, _RET_IP_);
2865 
2866 	xlog_cil_force(log);
2867 
2868 	spin_lock(&log->l_icloglock);
2869 	if (xlog_is_shutdown(log))
2870 		goto out_error;
2871 
2872 	iclog = log->l_iclog;
2873 	trace_xlog_iclog_force(iclog, _RET_IP_);
2874 
2875 	if (iclog->ic_state == XLOG_STATE_DIRTY ||
2876 	    (iclog->ic_state == XLOG_STATE_ACTIVE &&
2877 	     atomic_read(&iclog->ic_refcnt) == 0 && iclog->ic_offset == 0)) {
2878 		/*
2879 		 * If the head is dirty or (active and empty), then we need to
2880 		 * look at the previous iclog.
2881 		 *
2882 		 * If the previous iclog is active or dirty we are done.  There
2883 		 * is nothing to sync out. Otherwise, we attach ourselves to the
2884 		 * previous iclog and go to sleep.
2885 		 */
2886 		iclog = iclog->ic_prev;
2887 	} else if (iclog->ic_state == XLOG_STATE_ACTIVE) {
2888 		if (atomic_read(&iclog->ic_refcnt) == 0) {
2889 			/* We have exclusive access to this iclog. */
2890 			bool	completed;
2891 
2892 			if (xlog_force_and_check_iclog(iclog, &completed))
2893 				goto out_error;
2894 
2895 			if (completed)
2896 				goto out_unlock;
2897 		} else {
2898 			/*
2899 			 * Someone else is still writing to this iclog, so we
2900 			 * need to ensure that when they release the iclog it
2901 			 * gets synced immediately as we may be waiting on it.
2902 			 */
2903 			xlog_state_switch_iclogs(log, iclog, 0);
2904 		}
2905 	}
2906 
2907 	/*
2908 	 * The iclog we are about to wait on may contain the checkpoint pushed
2909 	 * by the above xlog_cil_force() call, but it may not have been pushed
2910 	 * to disk yet. Like the ACTIVE case above, we need to make sure caches
2911 	 * are flushed when this iclog is written.
2912 	 */
2913 	if (iclog->ic_state == XLOG_STATE_WANT_SYNC)
2914 		iclog->ic_flags |= XLOG_ICL_NEED_FLUSH | XLOG_ICL_NEED_FUA;
2915 
2916 	if (flags & XFS_LOG_SYNC)
2917 		return xlog_wait_on_iclog(iclog);
2918 out_unlock:
2919 	spin_unlock(&log->l_icloglock);
2920 	return 0;
2921 out_error:
2922 	spin_unlock(&log->l_icloglock);
2923 	return -EIO;
2924 }
2925 
2926 /*
2927  * Force the log to a specific LSN.
2928  *
2929  * If an iclog with that lsn can be found:
2930  *	If it is in the DIRTY state, just return.
2931  *	If it is in the ACTIVE state, move the in-core log into the WANT_SYNC
2932  *		state and go to sleep or return.
2933  *	If it is in any other state, go to sleep or return.
2934  *
2935  * Synchronous forces are implemented with a wait queue.  All callers trying
2936  * to force a given lsn to disk must wait on the queue attached to the
2937  * specific in-core log.  When given in-core log finally completes its write
2938  * to disk, that thread will wake up all threads waiting on the queue.
2939  */
2940 static int
2941 xlog_force_lsn(
2942 	struct xlog		*log,
2943 	xfs_lsn_t		lsn,
2944 	uint			flags,
2945 	int			*log_flushed,
2946 	bool			already_slept)
2947 {
2948 	struct xlog_in_core	*iclog;
2949 	bool			completed;
2950 
2951 	spin_lock(&log->l_icloglock);
2952 	if (xlog_is_shutdown(log))
2953 		goto out_error;
2954 
2955 	iclog = log->l_iclog;
2956 	while (be64_to_cpu(iclog->ic_header->h_lsn) != lsn) {
2957 		trace_xlog_iclog_force_lsn(iclog, _RET_IP_);
2958 		iclog = iclog->ic_next;
2959 		if (iclog == log->l_iclog)
2960 			goto out_unlock;
2961 	}
2962 
2963 	switch (iclog->ic_state) {
2964 	case XLOG_STATE_ACTIVE:
2965 		/*
2966 		 * We sleep here if we haven't already slept (e.g. this is the
2967 		 * first time we've looked at the correct iclog buf) and the
2968 		 * buffer before us is going to be sync'ed.  The reason for this
2969 		 * is that if we are doing sync transactions here, by waiting
2970 		 * for the previous I/O to complete, we can allow a few more
2971 		 * transactions into this iclog before we close it down.
2972 		 *
2973 		 * Otherwise, we mark the buffer WANT_SYNC, and bump up the
2974 		 * refcnt so we can release the log (which drops the ref count).
2975 		 * The state switch keeps new transaction commits from using
2976 		 * this buffer.  When the current commits finish writing into
2977 		 * the buffer, the refcount will drop to zero and the buffer
2978 		 * will go out then.
2979 		 */
2980 		if (!already_slept &&
2981 		    (iclog->ic_prev->ic_state == XLOG_STATE_WANT_SYNC ||
2982 		     iclog->ic_prev->ic_state == XLOG_STATE_SYNCING)) {
2983 			xlog_wait(&iclog->ic_prev->ic_write_wait,
2984 					&log->l_icloglock);
2985 			return -EAGAIN;
2986 		}
2987 		if (xlog_force_and_check_iclog(iclog, &completed))
2988 			goto out_error;
2989 		if (log_flushed)
2990 			*log_flushed = 1;
2991 		if (completed)
2992 			goto out_unlock;
2993 		break;
2994 	case XLOG_STATE_WANT_SYNC:
2995 		/*
2996 		 * This iclog may contain the checkpoint pushed by the
2997 		 * xlog_cil_force_seq() call, but there are other writers still
2998 		 * accessing it so it hasn't been pushed to disk yet. Like the
2999 		 * ACTIVE case above, we need to make sure caches are flushed
3000 		 * when this iclog is written.
3001 		 */
3002 		iclog->ic_flags |= XLOG_ICL_NEED_FLUSH | XLOG_ICL_NEED_FUA;
3003 		break;
3004 	default:
3005 		/*
3006 		 * The entire checkpoint was written by the CIL force and is on
3007 		 * its way to disk already. It will be stable when it
3008 		 * completes, so we don't need to manipulate caches here at all.
3009 		 * We just need to wait for completion if necessary.
3010 		 */
3011 		break;
3012 	}
3013 
3014 	if (flags & XFS_LOG_SYNC)
3015 		return xlog_wait_on_iclog(iclog);
3016 out_unlock:
3017 	spin_unlock(&log->l_icloglock);
3018 	return 0;
3019 out_error:
3020 	spin_unlock(&log->l_icloglock);
3021 	return -EIO;
3022 }
3023 
3024 /*
3025  * Force the log to a specific checkpoint sequence.
3026  *
3027  * First force the CIL so that all the required changes have been flushed to the
3028  * iclogs. If the CIL force completed it will return a commit LSN that indicates
3029  * the iclog that needs to be flushed to stable storage. If the caller needs
3030  * a synchronous log force, we will wait on the iclog with the LSN returned by
3031  * xlog_cil_force_seq() to be completed.
3032  */
3033 int
3034 xfs_log_force_seq(
3035 	struct xfs_mount	*mp,
3036 	xfs_csn_t		seq,
3037 	uint			flags,
3038 	int			*log_flushed)
3039 {
3040 	struct xlog		*log = mp->m_log;
3041 	xfs_lsn_t		lsn;
3042 	int			ret;
3043 	ASSERT(seq != 0);
3044 
3045 	XFS_STATS_INC(mp, xs_log_force);
3046 	trace_xfs_log_force(mp, seq, _RET_IP_);
3047 
3048 	lsn = xlog_cil_force_seq(log, seq);
3049 	if (lsn == NULLCOMMITLSN)
3050 		return 0;
3051 
3052 	ret = xlog_force_lsn(log, lsn, flags, log_flushed, false);
3053 	if (ret == -EAGAIN) {
3054 		XFS_STATS_INC(mp, xs_log_force_sleep);
3055 		ret = xlog_force_lsn(log, lsn, flags, log_flushed, true);
3056 	}
3057 	return ret;
3058 }
3059 
3060 /*
3061  * Free a used ticket when its refcount falls to zero.
3062  */
3063 void
3064 xfs_log_ticket_put(
3065 	struct xlog_ticket	*ticket)
3066 {
3067 	ASSERT(atomic_read(&ticket->t_ref) > 0);
3068 	if (atomic_dec_and_test(&ticket->t_ref))
3069 		kmem_cache_free(xfs_log_ticket_cache, ticket);
3070 }
3071 
3072 struct xlog_ticket *
3073 xfs_log_ticket_get(
3074 	struct xlog_ticket	*ticket)
3075 {
3076 	ASSERT(atomic_read(&ticket->t_ref) > 0);
3077 	atomic_inc(&ticket->t_ref);
3078 	return ticket;
3079 }
3080 
3081 /*
3082  * Figure out the total log space unit (in bytes) that would be
3083  * required for a log ticket.
3084  */
3085 static int
3086 xlog_calc_unit_res(
3087 	struct xlog		*log,
3088 	int			unit_bytes,
3089 	int			*niclogs)
3090 {
3091 	int			iclog_space;
3092 	uint			num_headers;
3093 
3094 	/*
3095 	 * Permanent reservations have up to 'cnt'-1 active log operations
3096 	 * in the log.  A unit in this case is the amount of space for one
3097 	 * of these log operations.  Normal reservations have a cnt of 1
3098 	 * and their unit amount is the total amount of space required.
3099 	 *
3100 	 * The following lines of code account for non-transaction data
3101 	 * which occupy space in the on-disk log.
3102 	 *
3103 	 * Normal form of a transaction is:
3104 	 * <oph><trans-hdr><start-oph><reg1-oph><reg1><reg2-oph>...<commit-oph>
3105 	 * and then there are LR hdrs, split-recs and roundoff at end of syncs.
3106 	 *
3107 	 * We need to account for all the leadup data and trailer data
3108 	 * around the transaction data.
3109 	 * And then we need to account for the worst case in terms of using
3110 	 * more space.
3111 	 * The worst case will happen if:
3112 	 * - the placement of the transaction happens to be such that the
3113 	 *   roundoff is at its maximum
3114 	 * - the transaction data is synced before the commit record is synced
3115 	 *   i.e. <transaction-data><roundoff> | <commit-rec><roundoff>
3116 	 *   Therefore the commit record is in its own Log Record.
3117 	 *   This can happen as the commit record is called with its
3118 	 *   own region to xlog_write().
3119 	 *   This then means that in the worst case, roundoff can happen for
3120 	 *   the commit-rec as well.
3121 	 *   The commit-rec is smaller than padding in this scenario and so it is
3122 	 *   not added separately.
3123 	 */
3124 
3125 	/* for trans header */
3126 	unit_bytes += sizeof(struct xlog_op_header);
3127 	unit_bytes += sizeof(struct xfs_trans_header);
3128 
3129 	/* for start-rec */
3130 	unit_bytes += sizeof(struct xlog_op_header);
3131 
3132 	/*
3133 	 * for LR headers - the space for data in an iclog is the size minus
3134 	 * the space used for the headers. If we use the iclog size, then we
3135 	 * undercalculate the number of headers required.
3136 	 *
3137 	 * Furthermore - the addition of op headers for split-recs might
3138 	 * increase the space required enough to require more log and op
3139 	 * headers, so take that into account too.
3140 	 *
3141 	 * IMPORTANT: This reservation makes the assumption that if this
3142 	 * transaction is the first in an iclog and hence has the LR headers
3143 	 * accounted to it, then the remaining space in the iclog is
3144 	 * exclusively for this transaction.  i.e. if the transaction is larger
3145 	 * than the iclog, it will be the only thing in that iclog.
3146 	 * Fundamentally, this means we must pass the entire log vector to
3147 	 * xlog_write to guarantee this.
3148 	 */
3149 	iclog_space = log->l_iclog_size - log->l_iclog_hsize;
3150 	num_headers = howmany(unit_bytes, iclog_space);
3151 
3152 	/* for split-recs - ophdrs added when data split over LRs */
3153 	unit_bytes += sizeof(struct xlog_op_header) * num_headers;
3154 
3155 	/* add extra header reservations if we overrun */
3156 	while (!num_headers ||
3157 	       howmany(unit_bytes, iclog_space) > num_headers) {
3158 		unit_bytes += sizeof(struct xlog_op_header);
3159 		num_headers++;
3160 	}
3161 	unit_bytes += log->l_iclog_hsize * num_headers;
3162 
3163 	/* for commit-rec LR header - note: padding will subsume the ophdr */
3164 	unit_bytes += log->l_iclog_hsize;
3165 
3166 	/* roundoff padding for transaction data and one for commit record */
3167 	unit_bytes += 2 * log->l_iclog_roundoff;
3168 
3169 	if (niclogs)
3170 		*niclogs = num_headers;
3171 	return unit_bytes;
3172 }
3173 
3174 int
3175 xfs_log_calc_unit_res(
3176 	struct xfs_mount	*mp,
3177 	int			unit_bytes)
3178 {
3179 	return xlog_calc_unit_res(mp->m_log, unit_bytes, NULL);
3180 }
3181 
3182 /*
3183  * Allocate and initialise a new log ticket.
3184  */
3185 struct xlog_ticket *
3186 xlog_ticket_alloc(
3187 	struct xlog		*log,
3188 	int			unit_bytes,
3189 	int			cnt,
3190 	bool			permanent)
3191 {
3192 	struct xlog_ticket	*tic;
3193 	int			unit_res;
3194 
3195 	tic = kmem_cache_zalloc(xfs_log_ticket_cache,
3196 			GFP_KERNEL | __GFP_NOFAIL);
3197 
3198 	unit_res = xlog_calc_unit_res(log, unit_bytes, &tic->t_iclog_hdrs);
3199 
3200 	atomic_set(&tic->t_ref, 1);
3201 	tic->t_task		= current;
3202 	INIT_LIST_HEAD(&tic->t_queue);
3203 	tic->t_unit_res		= unit_res;
3204 	tic->t_curr_res		= unit_res;
3205 	tic->t_cnt		= cnt;
3206 	tic->t_ocnt		= cnt;
3207 	tic->t_tid		= get_random_u32();
3208 	if (permanent)
3209 		tic->t_flags |= XLOG_TIC_PERM_RESERV;
3210 
3211 	return tic;
3212 }
3213 
3214 #if defined(DEBUG)
3215 static void
3216 xlog_verify_dump_tail(
3217 	struct xlog		*log,
3218 	struct xlog_in_core	*iclog)
3219 {
3220 	xfs_alert(log->l_mp,
3221 "ran out of log space tail 0x%llx/0x%llx, head lsn 0x%llx, head 0x%x/0x%x, prev head 0x%x/0x%x",
3222 			iclog ? be64_to_cpu(iclog->ic_header->h_tail_lsn) : -1,
3223 			atomic64_read(&log->l_tail_lsn),
3224 			log->l_ailp->ail_head_lsn,
3225 			log->l_curr_cycle, log->l_curr_block,
3226 			log->l_prev_cycle, log->l_prev_block);
3227 	xfs_alert(log->l_mp,
3228 "write grant 0x%llx, reserve grant 0x%llx, tail_space 0x%llx, size 0x%x, iclog flags 0x%x",
3229 			atomic64_read(&log->l_write_head.grant),
3230 			atomic64_read(&log->l_reserve_head.grant),
3231 			log->l_tail_space, log->l_logsize,
3232 			iclog ? iclog->ic_flags : -1);
3233 }
3234 
3235 /* Check if the new iclog will fit in the log. */
3236 STATIC void
3237 xlog_verify_tail_lsn(
3238 	struct xlog		*log,
3239 	struct xlog_in_core	*iclog)
3240 {
3241 	xfs_lsn_t	tail_lsn = be64_to_cpu(iclog->ic_header->h_tail_lsn);
3242 	int		blocks;
3243 
3244 	if (CYCLE_LSN(tail_lsn) == log->l_prev_cycle) {
3245 		blocks = log->l_logBBsize -
3246 				(log->l_prev_block - BLOCK_LSN(tail_lsn));
3247 		if (blocks < BTOBB(iclog->ic_offset) +
3248 					BTOBB(log->l_iclog_hsize)) {
3249 			xfs_emerg(log->l_mp,
3250 					"%s: ran out of log space", __func__);
3251 			xlog_verify_dump_tail(log, iclog);
3252 		}
3253 		return;
3254 	}
3255 
3256 	if (CYCLE_LSN(tail_lsn) + 1 != log->l_prev_cycle) {
3257 		xfs_emerg(log->l_mp, "%s: head has wrapped tail.", __func__);
3258 		xlog_verify_dump_tail(log, iclog);
3259 		return;
3260 	}
3261 	if (BLOCK_LSN(tail_lsn) == log->l_prev_block) {
3262 		xfs_emerg(log->l_mp, "%s: tail wrapped", __func__);
3263 		xlog_verify_dump_tail(log, iclog);
3264 		return;
3265 	}
3266 
3267 	blocks = BLOCK_LSN(tail_lsn) - log->l_prev_block;
3268 	if (blocks < BTOBB(iclog->ic_offset) + 1) {
3269 		xfs_emerg(log->l_mp, "%s: ran out of iclog space", __func__);
3270 		xlog_verify_dump_tail(log, iclog);
3271 	}
3272 }
3273 
3274 /*
3275  * Perform a number of checks on the iclog before writing to disk.
3276  *
3277  * 1. Make sure the iclogs are still circular
3278  * 2. Make sure we have a good magic number
3279  * 3. Make sure we don't have magic numbers in the data
3280  * 4. Check fields of each log operation header for:
3281  *	A. Valid client identifier
3282  *	B. tid ptr value falls in valid ptr space (user space code)
3283  *	C. Length in log record header is correct according to the
3284  *		individual operation headers within record.
3285  * 5. When a bwrite will occur within 5 blocks of the front of the physical
3286  *	log, check the preceding blocks of the physical log to make sure all
3287  *	the cycle numbers agree with the current cycle number.
3288  */
3289 STATIC void
3290 xlog_verify_iclog(
3291 	struct xlog		*log,
3292 	struct xlog_in_core	*iclog,
3293 	int			count)
3294 {
3295 	struct xlog_rec_header	*rhead = iclog->ic_header;
3296 	struct xlog_in_core	*icptr;
3297 	void			*base_ptr, *ptr;
3298 	ptrdiff_t		field_offset;
3299 	uint8_t			clientid;
3300 	int			len, i, op_len;
3301 	int			idx;
3302 
3303 	/* check validity of iclog pointers */
3304 	spin_lock(&log->l_icloglock);
3305 	icptr = log->l_iclog;
3306 	for (i = 0; i < log->l_iclog_bufs; i++, icptr = icptr->ic_next)
3307 		ASSERT(icptr);
3308 
3309 	if (icptr != log->l_iclog)
3310 		xfs_emerg(log->l_mp, "%s: corrupt iclog ring", __func__);
3311 	spin_unlock(&log->l_icloglock);
3312 
3313 	/* check log magic numbers */
3314 	if (rhead->h_magicno != cpu_to_be32(XLOG_HEADER_MAGIC_NUM))
3315 		xfs_emerg(log->l_mp, "%s: invalid magic num", __func__);
3316 
3317 	base_ptr = ptr = rhead;
3318 	for (ptr += BBSIZE; ptr < base_ptr + count; ptr += BBSIZE) {
3319 		if (*(__be32 *)ptr == cpu_to_be32(XLOG_HEADER_MAGIC_NUM))
3320 			xfs_emerg(log->l_mp, "%s: unexpected magic num",
3321 				__func__);
3322 	}
3323 
3324 	/* check fields */
3325 	len = be32_to_cpu(rhead->h_num_logops);
3326 	base_ptr = ptr = iclog->ic_datap;
3327 	for (i = 0; i < len; i++) {
3328 		struct xlog_op_header	*ophead = ptr;
3329 		void			*p = &ophead->oh_clientid;
3330 
3331 		/* clientid is only 1 byte */
3332 		field_offset = p - base_ptr;
3333 		if (field_offset & 0x1ff) {
3334 			clientid = ophead->oh_clientid;
3335 		} else {
3336 			idx = BTOBBT((void *)&ophead->oh_clientid - iclog->ic_datap);
3337 			clientid = xlog_get_client_id(*xlog_cycle_data(rhead, idx));
3338 		}
3339 		if (clientid != XFS_TRANSACTION && clientid != XFS_LOG) {
3340 			xfs_warn(log->l_mp,
3341 				"%s: op %d invalid clientid %d op "PTR_FMT" offset 0x%lx",
3342 				__func__, i, clientid, ophead,
3343 				(unsigned long)field_offset);
3344 		}
3345 
3346 		/* check length */
3347 		p = &ophead->oh_len;
3348 		field_offset = p - base_ptr;
3349 		if (field_offset & 0x1ff) {
3350 			op_len = be32_to_cpu(ophead->oh_len);
3351 		} else {
3352 			idx = BTOBBT((void *)&ophead->oh_len - iclog->ic_datap);
3353 			op_len = be32_to_cpu(*xlog_cycle_data(rhead, idx));
3354 		}
3355 		ptr += sizeof(struct xlog_op_header) + op_len;
3356 	}
3357 }
3358 #endif
3359 
3360 /*
3361  * Perform a forced shutdown on the log.
3362  *
3363  * This can be called from low level log code to trigger a shutdown, or from the
3364  * high level mount shutdown code when the mount shuts down.
3365  *
3366  * Our main objectives here are to make sure that:
3367  *	a. if the shutdown was not due to a log IO error, flush the logs to
3368  *	   disk. Anything modified after this is ignored.
3369  *	b. the log gets atomically marked 'XLOG_IO_ERROR' for all interested
3370  *	   parties to find out. Nothing new gets queued after this is done.
3371  *	c. Tasks sleeping on log reservations, pinned objects and
3372  *	   other resources get woken up.
3373  *	d. The mount is also marked as shut down so that log triggered shutdowns
3374  *	   still behave the same as if they called xfs_forced_shutdown().
3375  *
3376  * Return true if the shutdown cause was a log IO error and we actually shut the
3377  * log down.
3378  */
3379 bool
3380 xlog_force_shutdown(
3381 	struct xlog	*log,
3382 	uint32_t	shutdown_flags)
3383 {
3384 	bool		log_error = (shutdown_flags & SHUTDOWN_LOG_IO_ERROR);
3385 
3386 	if (!log)
3387 		return false;
3388 
3389 	/*
3390 	 * Ensure that there is only ever one log shutdown being processed.
3391 	 * If we allow the log force below on a second pass after shutting
3392 	 * down the log, we risk deadlocking the CIL push as it may require
3393 	 * locks on objects the current shutdown context holds (e.g. taking
3394 	 * buffer locks to abort buffers on last unpin of buf log items).
3395 	 */
3396 	if (test_and_set_bit(XLOG_SHUTDOWN_STARTED, &log->l_opstate))
3397 		return false;
3398 
3399 	/*
3400 	 * Flush all the completed transactions to disk before marking the log
3401 	 * being shut down. We need to do this first as shutting down the log
3402 	 * before the force will prevent the log force from flushing the iclogs
3403 	 * to disk.
3404 	 *
3405 	 * When we are in recovery, there are no transactions to flush, and
3406 	 * we don't want to touch the log because we don't want to perturb the
3407 	 * current head/tail for future recovery attempts. Hence we need to
3408 	 * avoid a log force in this case.
3409 	 *
3410 	 * If we are shutting down due to a log IO error, then we must avoid
3411 	 * trying to write the log as that may just result in more IO errors and
3412 	 * an endless shutdown/force loop.
3413 	 */
3414 	if (!log_error && !xlog_in_recovery(log))
3415 		xfs_log_force(log->l_mp, XFS_LOG_SYNC);
3416 
3417 	/*
3418 	 * Atomically set the shutdown state. If the shutdown state is already
3419 	 * set, there someone else is performing the shutdown and so we are done
3420 	 * here. This should never happen because we should only ever get called
3421 	 * once by the first shutdown caller.
3422 	 *
3423 	 * Much of the log state machine transitions assume that shutdown state
3424 	 * cannot change once they hold the log->l_icloglock. Hence we need to
3425 	 * hold that lock here, even though we use the atomic test_and_set_bit()
3426 	 * operation to set the shutdown state.
3427 	 */
3428 	spin_lock(&log->l_icloglock);
3429 	if (test_and_set_bit(XLOG_IO_ERROR, &log->l_opstate)) {
3430 		spin_unlock(&log->l_icloglock);
3431 		ASSERT(0);
3432 		return false;
3433 	}
3434 	spin_unlock(&log->l_icloglock);
3435 
3436 	/*
3437 	 * If this log shutdown also sets the mount shutdown state, issue a
3438 	 * shutdown warning message.
3439 	 */
3440 	if (!xfs_set_shutdown(log->l_mp)) {
3441 		xfs_alert_tag(log->l_mp, XFS_PTAG_SHUTDOWN_LOGERROR,
3442 "Filesystem has been shut down due to log error (0x%x).",
3443 				shutdown_flags);
3444 		xfs_alert(log->l_mp,
3445 "Please unmount the filesystem and rectify the problem(s).");
3446 		if (xfs_error_level >= XFS_ERRLEVEL_HIGH)
3447 			xfs_stack_trace();
3448 	}
3449 
3450 	/*
3451 	 * We don't want anybody waiting for log reservations after this. That
3452 	 * means we have to wake up everybody queued up on reserveq as well as
3453 	 * writeq.  In addition, we make sure in xlog_{re}grant_log_space that
3454 	 * we don't enqueue anything once the SHUTDOWN flag is set, and this
3455 	 * action is protected by the grant locks.
3456 	 */
3457 	xlog_grant_head_wake_all(&log->l_reserve_head);
3458 	xlog_grant_head_wake_all(&log->l_write_head);
3459 
3460 	/*
3461 	 * Wake up everybody waiting on xfs_log_force. Wake the CIL push first
3462 	 * as if the log writes were completed. The abort handling in the log
3463 	 * item committed callback functions will do this again under lock to
3464 	 * avoid races.
3465 	 */
3466 	spin_lock(&log->l_cilp->xc_push_lock);
3467 	wake_up_all(&log->l_cilp->xc_start_wait);
3468 	wake_up_all(&log->l_cilp->xc_commit_wait);
3469 	spin_unlock(&log->l_cilp->xc_push_lock);
3470 
3471 	spin_lock(&log->l_icloglock);
3472 	xlog_state_shutdown_callbacks(log);
3473 	spin_unlock(&log->l_icloglock);
3474 
3475 	wake_up_var(&log->l_opstate);
3476 	if (IS_ENABLED(CONFIG_XFS_RT) && xfs_has_zoned(log->l_mp))
3477 		xfs_zoned_wake_all(log->l_mp);
3478 
3479 	return log_error;
3480 }
3481 
3482 STATIC int
3483 xlog_iclogs_empty(
3484 	struct xlog		*log)
3485 {
3486 	struct xlog_in_core	*iclog = log->l_iclog;
3487 
3488 	do {
3489 		/* endianness does not matter here, zero is zero in
3490 		 * any language.
3491 		 */
3492 		if (iclog->ic_header->h_num_logops)
3493 			return 0;
3494 		iclog = iclog->ic_next;
3495 	} while (iclog != log->l_iclog);
3496 
3497 	return 1;
3498 }
3499 
3500 /*
3501  * Verify that an LSN stamped into a piece of metadata is valid. This is
3502  * intended for use in read verifiers on v5 superblocks.
3503  */
3504 bool
3505 xfs_log_check_lsn(
3506 	struct xfs_mount	*mp,
3507 	xfs_lsn_t		lsn)
3508 {
3509 	struct xlog		*log = mp->m_log;
3510 	bool			valid;
3511 
3512 	/*
3513 	 * norecovery mode skips mount-time log processing and unconditionally
3514 	 * resets the in-core LSN. We can't validate in this mode, but
3515 	 * modifications are not allowed anyways so just return true.
3516 	 */
3517 	if (xfs_has_norecovery(mp))
3518 		return true;
3519 
3520 	/*
3521 	 * Some metadata LSNs are initialized to NULL (e.g., the agfl). This is
3522 	 * handled by recovery and thus safe to ignore here.
3523 	 */
3524 	if (lsn == NULLCOMMITLSN)
3525 		return true;
3526 
3527 	valid = xlog_valid_lsn(mp->m_log, lsn);
3528 
3529 	/* warn the user about what's gone wrong before verifier failure */
3530 	if (!valid) {
3531 		spin_lock(&log->l_icloglock);
3532 		xfs_warn(mp,
3533 "Corruption warning: Metadata has LSN (%d:%d) ahead of current LSN (%d:%d). "
3534 "Please unmount and run xfs_repair (>= v4.3) to resolve.",
3535 			 CYCLE_LSN(lsn), BLOCK_LSN(lsn),
3536 			 log->l_curr_cycle, log->l_curr_block);
3537 		spin_unlock(&log->l_icloglock);
3538 	}
3539 
3540 	return valid;
3541 }
3542