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