1 /*
2  * Copyright (c) 2000-2005 Silicon Graphics, Inc.
3  * All Rights Reserved.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it would be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write the Free Software Foundation,
16  * Inc.,  51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17  */
18 #include "xfs.h"
19 #include "xfs_fs.h"
20 #include "xfs_types.h"
21 #include "xfs_bit.h"
22 #include "xfs_log.h"
23 #include "xfs_inum.h"
24 #include "xfs_trans.h"
25 #include "xfs_sb.h"
26 #include "xfs_ag.h"
27 #include "xfs_dir.h"
28 #include "xfs_dir2.h"
29 #include "xfs_dmapi.h"
30 #include "xfs_mount.h"
31 #include "xfs_error.h"
32 #include "xfs_log_priv.h"
33 #include "xfs_buf_item.h"
34 #include "xfs_bmap_btree.h"
35 #include "xfs_alloc_btree.h"
36 #include "xfs_ialloc_btree.h"
37 #include "xfs_log_recover.h"
38 #include "xfs_trans_priv.h"
39 #include "xfs_dir_sf.h"
40 #include "xfs_dir2_sf.h"
41 #include "xfs_attr_sf.h"
42 #include "xfs_dinode.h"
43 #include "xfs_inode.h"
44 #include "xfs_rw.h"
45 
46 
47 #define xlog_write_adv_cnt(ptr, len, off, bytes) \
48 	{ (ptr) += (bytes); \
49 	  (len) -= (bytes); \
50 	  (off) += (bytes);}
51 
52 /* Local miscellaneous function prototypes */
53 STATIC int	 xlog_bdstrat_cb(struct xfs_buf *);
54 STATIC int	 xlog_commit_record(xfs_mount_t *mp, xlog_ticket_t *ticket,
55 				    xlog_in_core_t **, xfs_lsn_t *);
56 STATIC xlog_t *  xlog_alloc_log(xfs_mount_t	*mp,
57 				xfs_buftarg_t	*log_target,
58 				xfs_daddr_t	blk_offset,
59 				int		num_bblks);
60 STATIC int	 xlog_space_left(xlog_t *log, int cycle, int bytes);
61 STATIC int	 xlog_sync(xlog_t *log, xlog_in_core_t *iclog);
62 STATIC void	 xlog_dealloc_log(xlog_t *log);
63 STATIC int	 xlog_write(xfs_mount_t *mp, xfs_log_iovec_t region[],
64 			    int nentries, xfs_log_ticket_t tic,
65 			    xfs_lsn_t *start_lsn,
66 			    xlog_in_core_t **commit_iclog,
67 			    uint flags);
68 
69 /* local state machine functions */
70 STATIC void xlog_state_done_syncing(xlog_in_core_t *iclog, int);
71 STATIC void xlog_state_do_callback(xlog_t *log,int aborted, xlog_in_core_t *iclog);
72 STATIC int  xlog_state_get_iclog_space(xlog_t		*log,
73 				       int		len,
74 				       xlog_in_core_t	**iclog,
75 				       xlog_ticket_t	*ticket,
76 				       int		*continued_write,
77 				       int		*logoffsetp);
78 STATIC void xlog_state_put_ticket(xlog_t	*log,
79 				  xlog_ticket_t *tic);
80 STATIC int  xlog_state_release_iclog(xlog_t		*log,
81 				     xlog_in_core_t	*iclog);
82 STATIC void xlog_state_switch_iclogs(xlog_t		*log,
83 				     xlog_in_core_t *iclog,
84 				     int		eventual_size);
85 STATIC int  xlog_state_sync(xlog_t			*log,
86 			    xfs_lsn_t 			lsn,
87 			    uint			flags,
88 			    int				*log_flushed);
89 STATIC int  xlog_state_sync_all(xlog_t *log, uint flags, int *log_flushed);
90 STATIC void xlog_state_want_sync(xlog_t	*log, xlog_in_core_t *iclog);
91 
92 /* local functions to manipulate grant head */
93 STATIC int  xlog_grant_log_space(xlog_t		*log,
94 				 xlog_ticket_t	*xtic);
95 STATIC void xlog_grant_push_ail(xfs_mount_t	*mp,
96 				int		need_bytes);
97 STATIC void xlog_regrant_reserve_log_space(xlog_t	 *log,
98 					   xlog_ticket_t *ticket);
99 STATIC int xlog_regrant_write_log_space(xlog_t		*log,
100 					 xlog_ticket_t  *ticket);
101 STATIC void xlog_ungrant_log_space(xlog_t	 *log,
102 				   xlog_ticket_t *ticket);
103 
104 
105 /* local ticket functions */
106 STATIC void		xlog_state_ticket_alloc(xlog_t *log);
107 STATIC xlog_ticket_t	*xlog_ticket_get(xlog_t *log,
108 					 int	unit_bytes,
109 					 int	count,
110 					 char	clientid,
111 					 uint	flags);
112 STATIC void		xlog_ticket_put(xlog_t *log, xlog_ticket_t *ticket);
113 
114 #if defined(DEBUG)
115 STATIC void	xlog_verify_dest_ptr(xlog_t *log, __psint_t ptr);
116 STATIC void	xlog_verify_grant_head(xlog_t *log, int equals);
117 STATIC void	xlog_verify_iclog(xlog_t *log, xlog_in_core_t *iclog,
118 				  int count, boolean_t syncing);
119 STATIC void	xlog_verify_tail_lsn(xlog_t *log, xlog_in_core_t *iclog,
120 				     xfs_lsn_t tail_lsn);
121 #else
122 #define xlog_verify_dest_ptr(a,b)
123 #define xlog_verify_grant_head(a,b)
124 #define xlog_verify_iclog(a,b,c,d)
125 #define xlog_verify_tail_lsn(a,b,c)
126 #endif
127 
128 STATIC int	xlog_iclogs_empty(xlog_t *log);
129 
130 #if defined(XFS_LOG_TRACE)
131 void
xlog_trace_loggrant(xlog_t * log,xlog_ticket_t * tic,xfs_caddr_t string)132 xlog_trace_loggrant(xlog_t *log, xlog_ticket_t *tic, xfs_caddr_t string)
133 {
134 	unsigned long cnts;
135 
136 	if (!log->l_grant_trace) {
137 		log->l_grant_trace = ktrace_alloc(2048, KM_NOSLEEP);
138 		if (!log->l_grant_trace)
139 			return;
140 	}
141 	/* ticket counts are 1 byte each */
142 	cnts = ((unsigned long)tic->t_ocnt) | ((unsigned long)tic->t_cnt) << 8;
143 
144 	ktrace_enter(log->l_grant_trace,
145 		     (void *)tic,
146 		     (void *)log->l_reserve_headq,
147 		     (void *)log->l_write_headq,
148 		     (void *)((unsigned long)log->l_grant_reserve_cycle),
149 		     (void *)((unsigned long)log->l_grant_reserve_bytes),
150 		     (void *)((unsigned long)log->l_grant_write_cycle),
151 		     (void *)((unsigned long)log->l_grant_write_bytes),
152 		     (void *)((unsigned long)log->l_curr_cycle),
153 		     (void *)((unsigned long)log->l_curr_block),
154 		     (void *)((unsigned long)CYCLE_LSN(log->l_tail_lsn)),
155 		     (void *)((unsigned long)BLOCK_LSN(log->l_tail_lsn)),
156 		     (void *)string,
157 		     (void *)((unsigned long)tic->t_trans_type),
158 		     (void *)cnts,
159 		     (void *)((unsigned long)tic->t_curr_res),
160 		     (void *)((unsigned long)tic->t_unit_res));
161 }
162 
163 void
xlog_trace_iclog(xlog_in_core_t * iclog,uint state)164 xlog_trace_iclog(xlog_in_core_t *iclog, uint state)
165 {
166 	if (!iclog->ic_trace)
167 		iclog->ic_trace = ktrace_alloc(256, KM_SLEEP);
168 	ktrace_enter(iclog->ic_trace,
169 		     (void *)((unsigned long)state),
170 		     (void *)((unsigned long)current_pid()),
171 		     (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL,
172 		     (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL,
173 		     (void *)NULL, (void *)NULL, (void *)NULL, (void *)NULL,
174 		     (void *)NULL, (void *)NULL);
175 }
176 #else
177 #define	xlog_trace_loggrant(log,tic,string)
178 #define	xlog_trace_iclog(iclog,state)
179 #endif /* XFS_LOG_TRACE */
180 
181 
182 static void
xlog_ins_ticketq(struct xlog_ticket ** qp,struct xlog_ticket * tic)183 xlog_ins_ticketq(struct xlog_ticket **qp, struct xlog_ticket *tic)
184 {
185 	if (*qp) {
186 		tic->t_next	    = (*qp);
187 		tic->t_prev	    = (*qp)->t_prev;
188 		(*qp)->t_prev->t_next = tic;
189 		(*qp)->t_prev	    = tic;
190 	} else {
191 		tic->t_prev = tic->t_next = tic;
192 		*qp = tic;
193 	}
194 
195 	tic->t_flags |= XLOG_TIC_IN_Q;
196 }
197 
198 static void
xlog_del_ticketq(struct xlog_ticket ** qp,struct xlog_ticket * tic)199 xlog_del_ticketq(struct xlog_ticket **qp, struct xlog_ticket *tic)
200 {
201 	if (tic == tic->t_next) {
202 		*qp = NULL;
203 	} else {
204 		*qp = tic->t_next;
205 		tic->t_next->t_prev = tic->t_prev;
206 		tic->t_prev->t_next = tic->t_next;
207 	}
208 
209 	tic->t_next = tic->t_prev = NULL;
210 	tic->t_flags &= ~XLOG_TIC_IN_Q;
211 }
212 
213 static void
xlog_grant_sub_space(struct log * log,int bytes)214 xlog_grant_sub_space(struct log *log, int bytes)
215 {
216 	log->l_grant_write_bytes -= bytes;
217 	if (log->l_grant_write_bytes < 0) {
218 		log->l_grant_write_bytes += log->l_logsize;
219 		log->l_grant_write_cycle--;
220 	}
221 
222 	log->l_grant_reserve_bytes -= bytes;
223 	if ((log)->l_grant_reserve_bytes < 0) {
224 		log->l_grant_reserve_bytes += log->l_logsize;
225 		log->l_grant_reserve_cycle--;
226 	}
227 
228 }
229 
230 static void
xlog_grant_add_space_write(struct log * log,int bytes)231 xlog_grant_add_space_write(struct log *log, int bytes)
232 {
233 	log->l_grant_write_bytes += bytes;
234 	if (log->l_grant_write_bytes > log->l_logsize) {
235 		log->l_grant_write_bytes -= log->l_logsize;
236 		log->l_grant_write_cycle++;
237 	}
238 }
239 
240 static void
xlog_grant_add_space_reserve(struct log * log,int bytes)241 xlog_grant_add_space_reserve(struct log *log, int bytes)
242 {
243 	log->l_grant_reserve_bytes += bytes;
244 	if (log->l_grant_reserve_bytes > log->l_logsize) {
245 		log->l_grant_reserve_bytes -= log->l_logsize;
246 		log->l_grant_reserve_cycle++;
247 	}
248 }
249 
250 static inline void
xlog_grant_add_space(struct log * log,int bytes)251 xlog_grant_add_space(struct log *log, int bytes)
252 {
253 	xlog_grant_add_space_write(log, bytes);
254 	xlog_grant_add_space_reserve(log, bytes);
255 }
256 
257 
258 /*
259  * NOTES:
260  *
261  *	1. currblock field gets updated at startup and after in-core logs
262  *		marked as with WANT_SYNC.
263  */
264 
265 /*
266  * This routine is called when a user of a log manager ticket is done with
267  * the reservation.  If the ticket was ever used, then a commit record for
268  * the associated transaction is written out as a log operation header with
269  * no data.  The flag XLOG_TIC_INITED is set when the first write occurs with
270  * a given ticket.  If the ticket was one with a permanent reservation, then
271  * a few operations are done differently.  Permanent reservation tickets by
272  * default don't release the reservation.  They just commit the current
273  * transaction with the belief that the reservation is still needed.  A flag
274  * must be passed in before permanent reservations are actually released.
275  * When these type of tickets are not released, they need to be set into
276  * the inited state again.  By doing this, a start record will be written
277  * out when the next write occurs.
278  */
279 xfs_lsn_t
xfs_log_done(xfs_mount_t * mp,xfs_log_ticket_t xtic,void ** iclog,uint flags)280 xfs_log_done(xfs_mount_t	*mp,
281 	     xfs_log_ticket_t	xtic,
282 	     void		**iclog,
283 	     uint		flags)
284 {
285 	xlog_t		*log    = mp->m_log;
286 	xlog_ticket_t	*ticket = (xfs_log_ticket_t) xtic;
287 	xfs_lsn_t	lsn	= 0;
288 
289 	if (XLOG_FORCED_SHUTDOWN(log) ||
290 	    /*
291 	     * If nothing was ever written, don't write out commit record.
292 	     * If we get an error, just continue and give back the log ticket.
293 	     */
294 	    (((ticket->t_flags & XLOG_TIC_INITED) == 0) &&
295 	     (xlog_commit_record(mp, ticket,
296 				 (xlog_in_core_t **)iclog, &lsn)))) {
297 		lsn = (xfs_lsn_t) -1;
298 		if (ticket->t_flags & XLOG_TIC_PERM_RESERV) {
299 			flags |= XFS_LOG_REL_PERM_RESERV;
300 		}
301 	}
302 
303 
304 	if ((ticket->t_flags & XLOG_TIC_PERM_RESERV) == 0 ||
305 	    (flags & XFS_LOG_REL_PERM_RESERV)) {
306 		/*
307 		 * Release ticket if not permanent reservation or a specific
308 		 * request has been made to release a permanent reservation.
309 		 */
310 		xlog_trace_loggrant(log, ticket, "xfs_log_done: (non-permanent)");
311 		xlog_ungrant_log_space(log, ticket);
312 		xlog_state_put_ticket(log, ticket);
313 	} else {
314 		xlog_trace_loggrant(log, ticket, "xfs_log_done: (permanent)");
315 		xlog_regrant_reserve_log_space(log, ticket);
316 	}
317 
318 	/* If this ticket was a permanent reservation and we aren't
319 	 * trying to release it, reset the inited flags; so next time
320 	 * we write, a start record will be written out.
321 	 */
322 	if ((ticket->t_flags & XLOG_TIC_PERM_RESERV) &&
323 	    (flags & XFS_LOG_REL_PERM_RESERV) == 0)
324 		ticket->t_flags |= XLOG_TIC_INITED;
325 
326 	return lsn;
327 }	/* xfs_log_done */
328 
329 
330 /*
331  * Force the in-core log to disk.  If flags == XFS_LOG_SYNC,
332  *	the force is done synchronously.
333  *
334  * Asynchronous forces are implemented by setting the WANT_SYNC
335  * bit in the appropriate in-core log and then returning.
336  *
337  * Synchronous forces are implemented with a semaphore.  All callers
338  * to force a given lsn to disk will wait on a semaphore attached to the
339  * specific in-core log.  When given in-core log finally completes its
340  * write to disk, that thread will wake up all threads waiting on the
341  * semaphore.
342  */
343 int
_xfs_log_force(xfs_mount_t * mp,xfs_lsn_t lsn,uint flags,int * log_flushed)344 _xfs_log_force(
345 	xfs_mount_t	*mp,
346 	xfs_lsn_t	lsn,
347 	uint		flags,
348 	int		*log_flushed)
349 {
350 	xlog_t		*log = mp->m_log;
351 	int		dummy;
352 
353 	if (!log_flushed)
354 		log_flushed = &dummy;
355 
356 	ASSERT(flags & XFS_LOG_FORCE);
357 
358 	XFS_STATS_INC(xs_log_force);
359 
360 	if (log->l_flags & XLOG_IO_ERROR)
361 		return XFS_ERROR(EIO);
362 	if (lsn == 0)
363 		return xlog_state_sync_all(log, flags, log_flushed);
364 	else
365 		return xlog_state_sync(log, lsn, flags, log_flushed);
366 }	/* xfs_log_force */
367 
368 /*
369  * Attaches a new iclog I/O completion callback routine during
370  * transaction commit.  If the log is in error state, a non-zero
371  * return code is handed back and the caller is responsible for
372  * executing the callback at an appropriate time.
373  */
374 int
xfs_log_notify(xfs_mount_t * mp,void * iclog_hndl,xfs_log_callback_t * cb)375 xfs_log_notify(xfs_mount_t	  *mp,		/* mount of partition */
376 	       void		  *iclog_hndl,	/* iclog to hang callback off */
377 	       xfs_log_callback_t *cb)
378 {
379 	xlog_t *log = mp->m_log;
380 	xlog_in_core_t	  *iclog = (xlog_in_core_t *)iclog_hndl;
381 	int	abortflg, spl;
382 
383 	cb->cb_next = NULL;
384 	spl = LOG_LOCK(log);
385 	abortflg = (iclog->ic_state & XLOG_STATE_IOERROR);
386 	if (!abortflg) {
387 		ASSERT_ALWAYS((iclog->ic_state == XLOG_STATE_ACTIVE) ||
388 			      (iclog->ic_state == XLOG_STATE_WANT_SYNC));
389 		cb->cb_next = NULL;
390 		*(iclog->ic_callback_tail) = cb;
391 		iclog->ic_callback_tail = &(cb->cb_next);
392 	}
393 	LOG_UNLOCK(log, spl);
394 	return abortflg;
395 }	/* xfs_log_notify */
396 
397 int
xfs_log_release_iclog(xfs_mount_t * mp,void * iclog_hndl)398 xfs_log_release_iclog(xfs_mount_t *mp,
399 		      void	  *iclog_hndl)
400 {
401 	xlog_t *log = mp->m_log;
402 	xlog_in_core_t	  *iclog = (xlog_in_core_t *)iclog_hndl;
403 
404 	if (xlog_state_release_iclog(log, iclog)) {
405 		xfs_force_shutdown(mp, XFS_LOG_IO_ERROR);
406 		return EIO;
407 	}
408 
409 	return 0;
410 }
411 
412 /*
413  *  1. Reserve an amount of on-disk log space and return a ticket corresponding
414  *	to the reservation.
415  *  2. Potentially, push buffers at tail of log to disk.
416  *
417  * Each reservation is going to reserve extra space for a log record header.
418  * When writes happen to the on-disk log, we don't subtract the length of the
419  * log record header from any reservation.  By wasting space in each
420  * reservation, we prevent over allocation problems.
421  */
422 int
xfs_log_reserve(xfs_mount_t * mp,int unit_bytes,int cnt,xfs_log_ticket_t * ticket,__uint8_t client,uint flags,uint t_type)423 xfs_log_reserve(xfs_mount_t	 *mp,
424 		int		 unit_bytes,
425 		int		 cnt,
426 		xfs_log_ticket_t *ticket,
427 		__uint8_t	 client,
428 		uint		 flags,
429 		uint		 t_type)
430 {
431 	xlog_t		*log = mp->m_log;
432 	xlog_ticket_t	*internal_ticket;
433 	int		retval = 0;
434 
435 	ASSERT(client == XFS_TRANSACTION || client == XFS_LOG);
436 	ASSERT((flags & XFS_LOG_NOSLEEP) == 0);
437 
438 	if (XLOG_FORCED_SHUTDOWN(log))
439 		return XFS_ERROR(EIO);
440 
441 	XFS_STATS_INC(xs_try_logspace);
442 
443 	if (*ticket != NULL) {
444 		ASSERT(flags & XFS_LOG_PERM_RESERV);
445 		internal_ticket = (xlog_ticket_t *)*ticket;
446 		xlog_trace_loggrant(log, internal_ticket, "xfs_log_reserve: existing ticket (permanent trans)");
447 		xlog_grant_push_ail(mp, internal_ticket->t_unit_res);
448 		retval = xlog_regrant_write_log_space(log, internal_ticket);
449 	} else {
450 		/* may sleep if need to allocate more tickets */
451 		internal_ticket = xlog_ticket_get(log, unit_bytes, cnt,
452 						  client, flags);
453 		internal_ticket->t_trans_type = t_type;
454 		*ticket = internal_ticket;
455 		xlog_trace_loggrant(log, internal_ticket,
456 			(internal_ticket->t_flags & XLOG_TIC_PERM_RESERV) ?
457 			"xfs_log_reserve: create new ticket (permanent trans)" :
458 			"xfs_log_reserve: create new ticket");
459 		xlog_grant_push_ail(mp,
460 				    (internal_ticket->t_unit_res *
461 				     internal_ticket->t_cnt));
462 		retval = xlog_grant_log_space(log, internal_ticket);
463 	}
464 
465 	return retval;
466 }	/* xfs_log_reserve */
467 
468 
469 /*
470  * Mount a log filesystem
471  *
472  * mp		- ubiquitous xfs mount point structure
473  * log_target	- buftarg of on-disk log device
474  * blk_offset	- Start block # where block size is 512 bytes (BBSIZE)
475  * num_bblocks	- Number of BBSIZE blocks in on-disk log
476  *
477  * Return error or zero.
478  */
479 int
xfs_log_mount(xfs_mount_t * mp,xfs_buftarg_t * log_target,xfs_daddr_t blk_offset,int num_bblks)480 xfs_log_mount(xfs_mount_t	*mp,
481 	      xfs_buftarg_t	*log_target,
482 	      xfs_daddr_t	blk_offset,
483 	      int		num_bblks)
484 {
485 	if (!(mp->m_flags & XFS_MOUNT_NORECOVERY))
486 		cmn_err(CE_NOTE, "XFS mounting filesystem %s", mp->m_fsname);
487 	else {
488 		cmn_err(CE_NOTE,
489 			"!Mounting filesystem \"%s\" in no-recovery mode.  Filesystem will be inconsistent.",
490 			mp->m_fsname);
491 		ASSERT(XFS_MTOVFS(mp)->vfs_flag & VFS_RDONLY);
492 	}
493 
494 	mp->m_log = xlog_alloc_log(mp, log_target, blk_offset, num_bblks);
495 
496 	/*
497 	 * skip log recovery on a norecovery mount.  pretend it all
498 	 * just worked.
499 	 */
500 	if (!(mp->m_flags & XFS_MOUNT_NORECOVERY)) {
501 		int		error;
502 		xfs_vfs_t	*vfsp = XFS_MTOVFS(mp);
503 		int		readonly = (vfsp->vfs_flag & VFS_RDONLY);
504 
505 		if (readonly)
506 			vfsp->vfs_flag &= ~VFS_RDONLY;
507 
508 		error = xlog_recover(mp->m_log);
509 
510 		if (readonly)
511 			vfsp->vfs_flag |= VFS_RDONLY;
512 		if (error) {
513 			cmn_err(CE_WARN, "XFS: log mount/recovery failed: error %d", error);
514 			xlog_dealloc_log(mp->m_log);
515 			return error;
516 		}
517 	}
518 
519 	/* Normal transactions can now occur */
520 	mp->m_log->l_flags &= ~XLOG_ACTIVE_RECOVERY;
521 
522 	/* End mounting message in xfs_log_mount_finish */
523 	return 0;
524 }	/* xfs_log_mount */
525 
526 /*
527  * Finish the recovery of the file system.  This is separate from
528  * the xfs_log_mount() call, because it depends on the code in
529  * xfs_mountfs() to read in the root and real-time bitmap inodes
530  * between calling xfs_log_mount() and here.
531  *
532  * mp		- ubiquitous xfs mount point structure
533  */
534 int
xfs_log_mount_finish(xfs_mount_t * mp,int mfsi_flags)535 xfs_log_mount_finish(xfs_mount_t *mp, int mfsi_flags)
536 {
537 	int	error;
538 
539 	if (!(mp->m_flags & XFS_MOUNT_NORECOVERY))
540 		error = xlog_recover_finish(mp->m_log, mfsi_flags);
541 	else {
542 		error = 0;
543 		ASSERT(XFS_MTOVFS(mp)->vfs_flag & VFS_RDONLY);
544 	}
545 
546 	return error;
547 }
548 
549 /*
550  * Unmount processing for the log.
551  */
552 int
xfs_log_unmount(xfs_mount_t * mp)553 xfs_log_unmount(xfs_mount_t *mp)
554 {
555 	int		error;
556 
557 	error = xfs_log_unmount_write(mp);
558 	xfs_log_unmount_dealloc(mp);
559 	return error;
560 }
561 
562 /*
563  * Final log writes as part of unmount.
564  *
565  * Mark the filesystem clean as unmount happens.  Note that during relocation
566  * this routine needs to be executed as part of source-bag while the
567  * deallocation must not be done until source-end.
568  */
569 
570 /*
571  * Unmount record used to have a string "Unmount filesystem--" in the
572  * data section where the "Un" was really a magic number (XLOG_UNMOUNT_TYPE).
573  * We just write the magic number now since that particular field isn't
574  * currently architecture converted and "nUmount" is a bit foo.
575  * As far as I know, there weren't any dependencies on the old behaviour.
576  */
577 
578 int
xfs_log_unmount_write(xfs_mount_t * mp)579 xfs_log_unmount_write(xfs_mount_t *mp)
580 {
581 	xlog_t		 *log = mp->m_log;
582 	xlog_in_core_t	 *iclog;
583 #ifdef DEBUG
584 	xlog_in_core_t	 *first_iclog;
585 #endif
586 	xfs_log_iovec_t  reg[1];
587 	xfs_log_ticket_t tic = NULL;
588 	xfs_lsn_t	 lsn;
589 	int		 error;
590 	SPLDECL(s);
591 
592 	/* the data section must be 32 bit size aligned */
593 	struct {
594 	    __uint16_t magic;
595 	    __uint16_t pad1;
596 	    __uint32_t pad2; /* may as well make it 64 bits */
597 	} magic = { XLOG_UNMOUNT_TYPE, 0, 0 };
598 
599 	/*
600 	 * Don't write out unmount record on read-only mounts.
601 	 * Or, if we are doing a forced umount (typically because of IO errors).
602 	 */
603 	if (XFS_MTOVFS(mp)->vfs_flag & VFS_RDONLY)
604 		return 0;
605 
606 	xfs_log_force(mp, 0, XFS_LOG_FORCE|XFS_LOG_SYNC);
607 
608 #ifdef DEBUG
609 	first_iclog = iclog = log->l_iclog;
610 	do {
611 		if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
612 			ASSERT(iclog->ic_state & XLOG_STATE_ACTIVE);
613 			ASSERT(iclog->ic_offset == 0);
614 		}
615 		iclog = iclog->ic_next;
616 	} while (iclog != first_iclog);
617 #endif
618 	if (! (XLOG_FORCED_SHUTDOWN(log))) {
619 		reg[0].i_addr = (void*)&magic;
620 		reg[0].i_len  = sizeof(magic);
621 		XLOG_VEC_SET_TYPE(&reg[0], XLOG_REG_TYPE_UNMOUNT);
622 
623 		error = xfs_log_reserve(mp, 600, 1, &tic, XFS_LOG, 0, 0);
624 		if (!error) {
625 			/* remove inited flag */
626 			((xlog_ticket_t *)tic)->t_flags = 0;
627 			error = xlog_write(mp, reg, 1, tic, &lsn,
628 					   NULL, XLOG_UNMOUNT_TRANS);
629 			/*
630 			 * At this point, we're umounting anyway,
631 			 * so there's no point in transitioning log state
632 			 * to IOERROR. Just continue...
633 			 */
634 		}
635 
636 		if (error) {
637 			xfs_fs_cmn_err(CE_ALERT, mp,
638 				"xfs_log_unmount: unmount record failed");
639 		}
640 
641 
642 		s = LOG_LOCK(log);
643 		iclog = log->l_iclog;
644 		iclog->ic_refcnt++;
645 		LOG_UNLOCK(log, s);
646 		xlog_state_want_sync(log, iclog);
647 		(void) xlog_state_release_iclog(log, iclog);
648 
649 		s = LOG_LOCK(log);
650 		if (!(iclog->ic_state == XLOG_STATE_ACTIVE ||
651 		      iclog->ic_state == XLOG_STATE_DIRTY)) {
652 			if (!XLOG_FORCED_SHUTDOWN(log)) {
653 				sv_wait(&iclog->ic_forcesema, PMEM,
654 					&log->l_icloglock, s);
655 			} else {
656 				LOG_UNLOCK(log, s);
657 			}
658 		} else {
659 			LOG_UNLOCK(log, s);
660 		}
661 		if (tic)
662 			xlog_state_put_ticket(log, tic);
663 	} else {
664 		/*
665 		 * We're already in forced_shutdown mode, couldn't
666 		 * even attempt to write out the unmount transaction.
667 		 *
668 		 * Go through the motions of sync'ing and releasing
669 		 * the iclog, even though no I/O will actually happen,
670 		 * we need to wait for other log I/Os that may already
671 		 * be in progress.  Do this as a separate section of
672 		 * code so we'll know if we ever get stuck here that
673 		 * we're in this odd situation of trying to unmount
674 		 * a file system that went into forced_shutdown as
675 		 * the result of an unmount..
676 		 */
677 		s = LOG_LOCK(log);
678 		iclog = log->l_iclog;
679 		iclog->ic_refcnt++;
680 		LOG_UNLOCK(log, s);
681 
682 		xlog_state_want_sync(log, iclog);
683 		(void) xlog_state_release_iclog(log, iclog);
684 
685 		s = LOG_LOCK(log);
686 
687 		if ( ! (   iclog->ic_state == XLOG_STATE_ACTIVE
688 			|| iclog->ic_state == XLOG_STATE_DIRTY
689 			|| iclog->ic_state == XLOG_STATE_IOERROR) ) {
690 
691 				sv_wait(&iclog->ic_forcesema, PMEM,
692 					&log->l_icloglock, s);
693 		} else {
694 			LOG_UNLOCK(log, s);
695 		}
696 	}
697 
698 	return 0;
699 }	/* xfs_log_unmount_write */
700 
701 /*
702  * Deallocate log structures for unmount/relocation.
703  */
704 void
xfs_log_unmount_dealloc(xfs_mount_t * mp)705 xfs_log_unmount_dealloc(xfs_mount_t *mp)
706 {
707 	xlog_dealloc_log(mp->m_log);
708 }
709 
710 /*
711  * Write region vectors to log.  The write happens using the space reservation
712  * of the ticket (tic).  It is not a requirement that all writes for a given
713  * transaction occur with one call to xfs_log_write().
714  */
715 int
xfs_log_write(xfs_mount_t * mp,xfs_log_iovec_t reg[],int nentries,xfs_log_ticket_t tic,xfs_lsn_t * start_lsn)716 xfs_log_write(xfs_mount_t *	mp,
717 	      xfs_log_iovec_t	reg[],
718 	      int		nentries,
719 	      xfs_log_ticket_t	tic,
720 	      xfs_lsn_t		*start_lsn)
721 {
722 	int	error;
723 	xlog_t *log = mp->m_log;
724 
725 	if (XLOG_FORCED_SHUTDOWN(log))
726 		return XFS_ERROR(EIO);
727 
728 	if ((error = xlog_write(mp, reg, nentries, tic, start_lsn, NULL, 0))) {
729 		xfs_force_shutdown(mp, XFS_LOG_IO_ERROR);
730 	}
731 	return error;
732 }	/* xfs_log_write */
733 
734 
735 void
xfs_log_move_tail(xfs_mount_t * mp,xfs_lsn_t tail_lsn)736 xfs_log_move_tail(xfs_mount_t	*mp,
737 		  xfs_lsn_t	tail_lsn)
738 {
739 	xlog_ticket_t	*tic;
740 	xlog_t		*log = mp->m_log;
741 	int		need_bytes, free_bytes, cycle, bytes;
742 	SPLDECL(s);
743 
744 	if (XLOG_FORCED_SHUTDOWN(log))
745 		return;
746 	ASSERT(!XFS_FORCED_SHUTDOWN(mp));
747 
748 	if (tail_lsn == 0) {
749 		/* needed since sync_lsn is 64 bits */
750 		s = LOG_LOCK(log);
751 		tail_lsn = log->l_last_sync_lsn;
752 		LOG_UNLOCK(log, s);
753 	}
754 
755 	s = GRANT_LOCK(log);
756 
757 	/* Also an invalid lsn.  1 implies that we aren't passing in a valid
758 	 * tail_lsn.
759 	 */
760 	if (tail_lsn != 1) {
761 		log->l_tail_lsn = tail_lsn;
762 	}
763 
764 	if ((tic = log->l_write_headq)) {
765 #ifdef DEBUG
766 		if (log->l_flags & XLOG_ACTIVE_RECOVERY)
767 			panic("Recovery problem");
768 #endif
769 		cycle = log->l_grant_write_cycle;
770 		bytes = log->l_grant_write_bytes;
771 		free_bytes = xlog_space_left(log, cycle, bytes);
772 		do {
773 			ASSERT(tic->t_flags & XLOG_TIC_PERM_RESERV);
774 
775 			if (free_bytes < tic->t_unit_res && tail_lsn != 1)
776 				break;
777 			tail_lsn = 0;
778 			free_bytes -= tic->t_unit_res;
779 			sv_signal(&tic->t_sema);
780 			tic = tic->t_next;
781 		} while (tic != log->l_write_headq);
782 	}
783 	if ((tic = log->l_reserve_headq)) {
784 #ifdef DEBUG
785 		if (log->l_flags & XLOG_ACTIVE_RECOVERY)
786 			panic("Recovery problem");
787 #endif
788 		cycle = log->l_grant_reserve_cycle;
789 		bytes = log->l_grant_reserve_bytes;
790 		free_bytes = xlog_space_left(log, cycle, bytes);
791 		do {
792 			if (tic->t_flags & XLOG_TIC_PERM_RESERV)
793 				need_bytes = tic->t_unit_res*tic->t_cnt;
794 			else
795 				need_bytes = tic->t_unit_res;
796 			if (free_bytes < need_bytes && tail_lsn != 1)
797 				break;
798 			tail_lsn = 0;
799 			free_bytes -= need_bytes;
800 			sv_signal(&tic->t_sema);
801 			tic = tic->t_next;
802 		} while (tic != log->l_reserve_headq);
803 	}
804 	GRANT_UNLOCK(log, s);
805 }	/* xfs_log_move_tail */
806 
807 /*
808  * Determine if we have a transaction that has gone to disk
809  * that needs to be covered. Log activity needs to be idle (no AIL and
810  * nothing in the iclogs). And, we need to be in the right state indicating
811  * something has gone out.
812  */
813 int
xfs_log_need_covered(xfs_mount_t * mp)814 xfs_log_need_covered(xfs_mount_t *mp)
815 {
816 	SPLDECL(s);
817 	int		needed = 0, gen;
818 	xlog_t		*log = mp->m_log;
819 	xfs_vfs_t	*vfsp = XFS_MTOVFS(mp);
820 
821 	if (/* fs_frozen(vfsp) RMC */ 0 || XFS_FORCED_SHUTDOWN(mp) ||
822 	    (vfsp->vfs_flag & VFS_RDONLY))
823 		return 0;
824 
825 	s = LOG_LOCK(log);
826 	if (((log->l_covered_state == XLOG_STATE_COVER_NEED) ||
827 		(log->l_covered_state == XLOG_STATE_COVER_NEED2))
828 			&& !xfs_trans_first_ail(mp, &gen)
829 			&& xlog_iclogs_empty(log)) {
830 		if (log->l_covered_state == XLOG_STATE_COVER_NEED)
831 			log->l_covered_state = XLOG_STATE_COVER_DONE;
832 		else {
833 			ASSERT(log->l_covered_state == XLOG_STATE_COVER_NEED2);
834 			log->l_covered_state = XLOG_STATE_COVER_DONE2;
835 		}
836 		needed = 1;
837 	}
838 	LOG_UNLOCK(log, s);
839 	return needed;
840 }
841 
842 /******************************************************************************
843  *
844  *	local routines
845  *
846  ******************************************************************************
847  */
848 
849 /* xfs_trans_tail_ail returns 0 when there is nothing in the list.
850  * The log manager must keep track of the last LR which was committed
851  * to disk.  The lsn of this LR will become the new tail_lsn whenever
852  * xfs_trans_tail_ail returns 0.  If we don't do this, we run into
853  * the situation where stuff could be written into the log but nothing
854  * was ever in the AIL when asked.  Eventually, we panic since the
855  * tail hits the head.
856  *
857  * We may be holding the log iclog lock upon entering this routine.
858  */
859 xfs_lsn_t
xlog_assign_tail_lsn(xfs_mount_t * mp)860 xlog_assign_tail_lsn(xfs_mount_t *mp)
861 {
862 	xfs_lsn_t tail_lsn;
863 	SPLDECL(s);
864 	xlog_t	  *log = mp->m_log;
865 
866 	tail_lsn = xfs_trans_tail_ail(mp);
867 	s = GRANT_LOCK(log);
868 	if (tail_lsn != 0) {
869 		log->l_tail_lsn = tail_lsn;
870 	} else {
871 		tail_lsn = log->l_tail_lsn = log->l_last_sync_lsn;
872 	}
873 	GRANT_UNLOCK(log, s);
874 
875 	return tail_lsn;
876 }	/* xlog_assign_tail_lsn */
877 
878 
879 /*
880  * Return the space in the log between the tail and the head.  The head
881  * is passed in the cycle/bytes formal parms.  In the special case where
882  * the reserve head has wrapped passed the tail, this calculation is no
883  * longer valid.  In this case, just return 0 which means there is no space
884  * in the log.  This works for all places where this function is called
885  * with the reserve head.  Of course, if the write head were to ever
886  * wrap the tail, we should blow up.  Rather than catch this case here,
887  * we depend on other ASSERTions in other parts of the code.   XXXmiken
888  *
889  * This code also handles the case where the reservation head is behind
890  * the tail.  The details of this case are described below, but the end
891  * result is that we return the size of the log as the amount of space left.
892  */
893 int
xlog_space_left(xlog_t * log,int cycle,int bytes)894 xlog_space_left(xlog_t *log, int cycle, int bytes)
895 {
896 	int free_bytes;
897 	int tail_bytes;
898 	int tail_cycle;
899 
900 	tail_bytes = BBTOB(BLOCK_LSN(log->l_tail_lsn));
901 	tail_cycle = CYCLE_LSN(log->l_tail_lsn);
902 	if ((tail_cycle == cycle) && (bytes >= tail_bytes)) {
903 		free_bytes = log->l_logsize - (bytes - tail_bytes);
904 	} else if ((tail_cycle + 1) < cycle) {
905 		return 0;
906 	} else if (tail_cycle < cycle) {
907 		ASSERT(tail_cycle == (cycle - 1));
908 		free_bytes = tail_bytes - bytes;
909 	} else {
910 		/*
911 		 * The reservation head is behind the tail.
912 		 * In this case we just want to return the size of the
913 		 * log as the amount of space left.
914 		 */
915 		xfs_fs_cmn_err(CE_ALERT, log->l_mp,
916 			"xlog_space_left: head behind tail\n"
917 			"  tail_cycle = %d, tail_bytes = %d\n"
918 			"  GH   cycle = %d, GH   bytes = %d",
919 			tail_cycle, tail_bytes, cycle, bytes);
920 		ASSERT(0);
921 		free_bytes = log->l_logsize;
922 	}
923 	return free_bytes;
924 }	/* xlog_space_left */
925 
926 
927 /*
928  * Log function which is called when an io completes.
929  *
930  * The log manager needs its own routine, in order to control what
931  * happens with the buffer after the write completes.
932  */
933 void
xlog_iodone(xfs_buf_t * bp)934 xlog_iodone(xfs_buf_t *bp)
935 {
936 	xlog_in_core_t	*iclog;
937 	xlog_t		*l;
938 	int		aborted;
939 
940 	iclog = XFS_BUF_FSPRIVATE(bp, xlog_in_core_t *);
941 	ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) == (unsigned long) 2);
942 	XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
943 	aborted = 0;
944 
945 	/*
946 	 * Some versions of cpp barf on the recursive definition of
947 	 * ic_log -> hic_fields.ic_log and expand ic_log twice when
948 	 * it is passed through two macros.  Workaround broken cpp.
949 	 */
950 	l = iclog->ic_log;
951 
952 	/*
953 	 * Race to shutdown the filesystem if we see an error.
954 	 */
955 	if (XFS_TEST_ERROR((XFS_BUF_GETERROR(bp)), l->l_mp,
956 			XFS_ERRTAG_IODONE_IOERR, XFS_RANDOM_IODONE_IOERR)) {
957 		xfs_ioerror_alert("xlog_iodone", l->l_mp, bp, XFS_BUF_ADDR(bp));
958 		XFS_BUF_STALE(bp);
959 		xfs_force_shutdown(l->l_mp, XFS_LOG_IO_ERROR);
960 		/*
961 		 * This flag will be propagated to the trans-committed
962 		 * callback routines to let them know that the log-commit
963 		 * didn't succeed.
964 		 */
965 		aborted = XFS_LI_ABORTED;
966 	} else if (iclog->ic_state & XLOG_STATE_IOERROR) {
967 		aborted = XFS_LI_ABORTED;
968 	}
969 	xlog_state_done_syncing(iclog, aborted);
970 	if (!(XFS_BUF_ISASYNC(bp))) {
971 		/*
972 		 * Corresponding psema() will be done in bwrite().  If we don't
973 		 * vsema() here, panic.
974 		 */
975 		XFS_BUF_V_IODONESEMA(bp);
976 	} else
977 		XFS_BUF_VSEMA(bp);
978 }	/* xlog_iodone */
979 
980 /*
981  * The bdstrat callback function for log bufs. This gives us a central
982  * place to trap bufs in case we get hit by a log I/O error and need to
983  * shutdown. Actually, in practice, even when we didn't get a log error,
984  * we transition the iclogs to IOERROR state *after* flushing all existing
985  * iclogs to disk. This is because we don't want anymore new transactions to be
986  * started or completed afterwards.
987  */
988 STATIC int
xlog_bdstrat_cb(struct xfs_buf * bp)989 xlog_bdstrat_cb(struct xfs_buf *bp)
990 {
991 	xlog_in_core_t *iclog;
992 
993 	iclog = XFS_BUF_FSPRIVATE(bp, xlog_in_core_t *);
994 
995 	if ((iclog->ic_state & XLOG_STATE_IOERROR) == 0) {
996 	  /* note for irix bstrat will need  struct bdevsw passed
997 	   * Fix the following macro if the code ever is merged
998 	   */
999 	    XFS_bdstrat(bp);
1000 		return 0;
1001 	}
1002 
1003 	xfs_buftrace("XLOG__BDSTRAT IOERROR", bp);
1004 	XFS_BUF_ERROR(bp, EIO);
1005 	XFS_BUF_STALE(bp);
1006 	xfs_biodone(bp);
1007 	return XFS_ERROR(EIO);
1008 
1009 
1010 }
1011 
1012 /*
1013  * Return size of each in-core log record buffer.
1014  *
1015  * Low memory machines only get 2 16KB buffers.  We don't want to waste
1016  * memory here.  However, all other machines get at least 2 32KB buffers.
1017  * The number is hard coded because we don't care about the minimum
1018  * memory size, just 32MB systems.
1019  *
1020  * If the filesystem blocksize is too large, we may need to choose a
1021  * larger size since the directory code currently logs entire blocks.
1022  */
1023 
1024 STATIC void
xlog_get_iclog_buffer_size(xfs_mount_t * mp,xlog_t * log)1025 xlog_get_iclog_buffer_size(xfs_mount_t	*mp,
1026 			   xlog_t	*log)
1027 {
1028 	int size;
1029 	int xhdrs;
1030 
1031 	if (mp->m_logbufs <= 0) {
1032 		if (xfs_physmem <= btoc(128*1024*1024)) {
1033 			log->l_iclog_bufs = XLOG_MIN_ICLOGS;
1034 		} else if (xfs_physmem <= btoc(400*1024*1024)) {
1035 			log->l_iclog_bufs = XLOG_MED_ICLOGS;
1036 		} else {	/* 256K with 32K bufs */
1037 			log->l_iclog_bufs = XLOG_MAX_ICLOGS;
1038 		}
1039 	} else {
1040 		log->l_iclog_bufs = mp->m_logbufs;
1041 	}
1042 
1043 	/*
1044 	 * Buffer size passed in from mount system call.
1045 	 */
1046 	if (mp->m_logbsize > 0) {
1047 		size = log->l_iclog_size = mp->m_logbsize;
1048 		log->l_iclog_size_log = 0;
1049 		while (size != 1) {
1050 			log->l_iclog_size_log++;
1051 			size >>= 1;
1052 		}
1053 
1054 		if (XFS_SB_VERSION_HASLOGV2(&mp->m_sb)) {
1055 			/* # headers = size / 32K
1056 			 * one header holds cycles from 32K of data
1057 			 */
1058 
1059 			xhdrs = mp->m_logbsize / XLOG_HEADER_CYCLE_SIZE;
1060 			if (mp->m_logbsize % XLOG_HEADER_CYCLE_SIZE)
1061 				xhdrs++;
1062 			log->l_iclog_hsize = xhdrs << BBSHIFT;
1063 			log->l_iclog_heads = xhdrs;
1064 		} else {
1065 			ASSERT(mp->m_logbsize <= XLOG_BIG_RECORD_BSIZE);
1066 			log->l_iclog_hsize = BBSIZE;
1067 			log->l_iclog_heads = 1;
1068 		}
1069 		goto done;
1070 	}
1071 
1072 	/*
1073 	 * Special case machines that have less than 32MB of memory.
1074 	 * All machines with more memory use 32KB buffers.
1075 	 */
1076 	if (xfs_physmem <= btoc(32*1024*1024)) {
1077 		/* Don't change; min configuration */
1078 		log->l_iclog_size = XLOG_RECORD_BSIZE;		/* 16k */
1079 		log->l_iclog_size_log = XLOG_RECORD_BSHIFT;
1080 	} else {
1081 		log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;	/* 32k */
1082 		log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
1083 	}
1084 
1085 	/* the default log size is 16k or 32k which is one header sector */
1086 	log->l_iclog_hsize = BBSIZE;
1087 	log->l_iclog_heads = 1;
1088 
1089 	/*
1090 	 * For 16KB, we use 3 32KB buffers.  For 32KB block sizes, we use
1091 	 * 4 32KB buffers.  For 64KB block sizes, we use 8 32KB buffers.
1092 	 */
1093 	if (mp->m_sb.sb_blocksize >= 16*1024) {
1094 		log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;
1095 		log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
1096 		if (mp->m_logbufs <= 0) {
1097 			switch (mp->m_sb.sb_blocksize) {
1098 			    case 16*1024:			/* 16 KB */
1099 				log->l_iclog_bufs = 3;
1100 				break;
1101 			    case 32*1024:			/* 32 KB */
1102 				log->l_iclog_bufs = 4;
1103 				break;
1104 			    case 64*1024:			/* 64 KB */
1105 				log->l_iclog_bufs = 8;
1106 				break;
1107 			    default:
1108 				xlog_panic("XFS: Invalid blocksize");
1109 				break;
1110 			}
1111 		}
1112 	}
1113 
1114 done:	/* are we being asked to make the sizes selected above visible? */
1115 	if (mp->m_logbufs == 0)
1116 		mp->m_logbufs = log->l_iclog_bufs;
1117 	if (mp->m_logbsize == 0)
1118 		mp->m_logbsize = log->l_iclog_size;
1119 }	/* xlog_get_iclog_buffer_size */
1120 
1121 
1122 /*
1123  * This routine initializes some of the log structure for a given mount point.
1124  * Its primary purpose is to fill in enough, so recovery can occur.  However,
1125  * some other stuff may be filled in too.
1126  */
1127 STATIC xlog_t *
xlog_alloc_log(xfs_mount_t * mp,xfs_buftarg_t * log_target,xfs_daddr_t blk_offset,int num_bblks)1128 xlog_alloc_log(xfs_mount_t	*mp,
1129 	       xfs_buftarg_t	*log_target,
1130 	       xfs_daddr_t	blk_offset,
1131 	       int		num_bblks)
1132 {
1133 	xlog_t			*log;
1134 	xlog_rec_header_t	*head;
1135 	xlog_in_core_t		**iclogp;
1136 	xlog_in_core_t		*iclog, *prev_iclog=NULL;
1137 	xfs_buf_t		*bp;
1138 	int			i;
1139 	int			iclogsize;
1140 
1141 	log = (xlog_t *)kmem_zalloc(sizeof(xlog_t), KM_SLEEP);
1142 
1143 	log->l_mp	   = mp;
1144 	log->l_targ	   = log_target;
1145 	log->l_logsize     = BBTOB(num_bblks);
1146 	log->l_logBBstart  = blk_offset;
1147 	log->l_logBBsize   = num_bblks;
1148 	log->l_covered_state = XLOG_STATE_COVER_IDLE;
1149 	log->l_flags	   |= XLOG_ACTIVE_RECOVERY;
1150 
1151 	log->l_prev_block  = -1;
1152 	ASSIGN_ANY_LSN_HOST(log->l_tail_lsn, 1, 0);
1153 	/* log->l_tail_lsn = 0x100000000LL; cycle = 1; current block = 0 */
1154 	log->l_last_sync_lsn = log->l_tail_lsn;
1155 	log->l_curr_cycle  = 1;	    /* 0 is bad since this is initial value */
1156 	log->l_grant_reserve_cycle = 1;
1157 	log->l_grant_write_cycle = 1;
1158 
1159 	if (XFS_SB_VERSION_HASSECTOR(&mp->m_sb)) {
1160 		log->l_sectbb_log = mp->m_sb.sb_logsectlog - BBSHIFT;
1161 		ASSERT(log->l_sectbb_log <= mp->m_sectbb_log);
1162 		/* for larger sector sizes, must have v2 or external log */
1163 		ASSERT(log->l_sectbb_log == 0 ||
1164 			log->l_logBBstart == 0 ||
1165 			XFS_SB_VERSION_HASLOGV2(&mp->m_sb));
1166 		ASSERT(mp->m_sb.sb_logsectlog >= BBSHIFT);
1167 	}
1168 	log->l_sectbb_mask = (1 << log->l_sectbb_log) - 1;
1169 
1170 	xlog_get_iclog_buffer_size(mp, log);
1171 
1172 	bp = xfs_buf_get_empty(log->l_iclog_size, mp->m_logdev_targp);
1173 	XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1174 	XFS_BUF_SET_BDSTRAT_FUNC(bp, xlog_bdstrat_cb);
1175 	XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
1176 	ASSERT(XFS_BUF_ISBUSY(bp));
1177 	ASSERT(XFS_BUF_VALUSEMA(bp) <= 0);
1178 	XFS_BUF_VSEMA(bp);
1179 	log->l_xbuf = bp;
1180 
1181 	spinlock_init(&log->l_icloglock, "iclog");
1182 	spinlock_init(&log->l_grant_lock, "grhead_iclog");
1183 	initnsema(&log->l_flushsema, 0, "ic-flush");
1184 	xlog_state_ticket_alloc(log);  /* wait until after icloglock inited */
1185 
1186 	/* log record size must be multiple of BBSIZE; see xlog_rec_header_t */
1187 	ASSERT((XFS_BUF_SIZE(bp) & BBMASK) == 0);
1188 
1189 	iclogp = &log->l_iclog;
1190 	/*
1191 	 * The amount of memory to allocate for the iclog structure is
1192 	 * rather funky due to the way the structure is defined.  It is
1193 	 * done this way so that we can use different sizes for machines
1194 	 * with different amounts of memory.  See the definition of
1195 	 * xlog_in_core_t in xfs_log_priv.h for details.
1196 	 */
1197 	iclogsize = log->l_iclog_size;
1198 	ASSERT(log->l_iclog_size >= 4096);
1199 	for (i=0; i < log->l_iclog_bufs; i++) {
1200 		*iclogp = (xlog_in_core_t *)
1201 			  kmem_zalloc(sizeof(xlog_in_core_t), KM_SLEEP);
1202 		iclog = *iclogp;
1203 		iclog->hic_data = (xlog_in_core_2_t *)
1204 			  kmem_zalloc(iclogsize, KM_SLEEP);
1205 
1206 		iclog->ic_prev = prev_iclog;
1207 		prev_iclog = iclog;
1208 		log->l_iclog_bak[i] = (xfs_caddr_t)&(iclog->ic_header);
1209 
1210 		head = &iclog->ic_header;
1211 		memset(head, 0, sizeof(xlog_rec_header_t));
1212 		INT_SET(head->h_magicno, ARCH_CONVERT, XLOG_HEADER_MAGIC_NUM);
1213 		INT_SET(head->h_version, ARCH_CONVERT,
1214 			XFS_SB_VERSION_HASLOGV2(&log->l_mp->m_sb) ? 2 : 1);
1215 		INT_SET(head->h_size, ARCH_CONVERT, log->l_iclog_size);
1216 		/* new fields */
1217 		INT_SET(head->h_fmt, ARCH_CONVERT, XLOG_FMT);
1218 		memcpy(&head->h_fs_uuid, &mp->m_sb.sb_uuid, sizeof(uuid_t));
1219 
1220 		bp = xfs_buf_get_empty(log->l_iclog_size, mp->m_logdev_targp);
1221 		XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1222 		XFS_BUF_SET_BDSTRAT_FUNC(bp, xlog_bdstrat_cb);
1223 		XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
1224 		iclog->ic_bp = bp;
1225 
1226 		iclog->ic_size = XFS_BUF_SIZE(bp) - log->l_iclog_hsize;
1227 		iclog->ic_state = XLOG_STATE_ACTIVE;
1228 		iclog->ic_log = log;
1229 		iclog->ic_callback_tail = &(iclog->ic_callback);
1230 		iclog->ic_datap = (char *)iclog->hic_data + log->l_iclog_hsize;
1231 
1232 		ASSERT(XFS_BUF_ISBUSY(iclog->ic_bp));
1233 		ASSERT(XFS_BUF_VALUSEMA(iclog->ic_bp) <= 0);
1234 		XFS_BUF_VSEMA(iclog->ic_bp);
1235 		sv_init(&iclog->ic_forcesema, SV_DEFAULT, "iclog-force");
1236 		sv_init(&iclog->ic_writesema, SV_DEFAULT, "iclog-write");
1237 
1238 		iclogp = &iclog->ic_next;
1239 	}
1240 	*iclogp = log->l_iclog;			/* complete ring */
1241 	log->l_iclog->ic_prev = prev_iclog;	/* re-write 1st prev ptr */
1242 
1243 	return log;
1244 }	/* xlog_alloc_log */
1245 
1246 
1247 /*
1248  * Write out the commit record of a transaction associated with the given
1249  * ticket.  Return the lsn of the commit record.
1250  */
1251 STATIC int
xlog_commit_record(xfs_mount_t * mp,xlog_ticket_t * ticket,xlog_in_core_t ** iclog,xfs_lsn_t * commitlsnp)1252 xlog_commit_record(xfs_mount_t  *mp,
1253 		   xlog_ticket_t *ticket,
1254 		   xlog_in_core_t **iclog,
1255 		   xfs_lsn_t	*commitlsnp)
1256 {
1257 	int		error;
1258 	xfs_log_iovec_t	reg[1];
1259 
1260 	reg[0].i_addr = NULL;
1261 	reg[0].i_len = 0;
1262 	XLOG_VEC_SET_TYPE(&reg[0], XLOG_REG_TYPE_COMMIT);
1263 
1264 	ASSERT_ALWAYS(iclog);
1265 	if ((error = xlog_write(mp, reg, 1, ticket, commitlsnp,
1266 			       iclog, XLOG_COMMIT_TRANS))) {
1267 		xfs_force_shutdown(mp, XFS_LOG_IO_ERROR);
1268 	}
1269 	return error;
1270 }	/* xlog_commit_record */
1271 
1272 
1273 /*
1274  * Push on the buffer cache code if we ever use more than 75% of the on-disk
1275  * log space.  This code pushes on the lsn which would supposedly free up
1276  * the 25% which we want to leave free.  We may need to adopt a policy which
1277  * pushes on an lsn which is further along in the log once we reach the high
1278  * water mark.  In this manner, we would be creating a low water mark.
1279  */
1280 void
xlog_grant_push_ail(xfs_mount_t * mp,int need_bytes)1281 xlog_grant_push_ail(xfs_mount_t	*mp,
1282 		    int		need_bytes)
1283 {
1284     xlog_t	*log = mp->m_log;	/* pointer to the log */
1285     xfs_lsn_t	tail_lsn;		/* lsn of the log tail */
1286     xfs_lsn_t	threshold_lsn = 0;	/* lsn we'd like to be at */
1287     int		free_blocks;		/* free blocks left to write to */
1288     int		free_bytes;		/* free bytes left to write to */
1289     int		threshold_block;	/* block in lsn we'd like to be at */
1290     int		threshold_cycle;	/* lsn cycle we'd like to be at */
1291     int		free_threshold;
1292     SPLDECL(s);
1293 
1294     ASSERT(BTOBB(need_bytes) < log->l_logBBsize);
1295 
1296     s = GRANT_LOCK(log);
1297     free_bytes = xlog_space_left(log,
1298 				 log->l_grant_reserve_cycle,
1299 				 log->l_grant_reserve_bytes);
1300     tail_lsn = log->l_tail_lsn;
1301     free_blocks = BTOBBT(free_bytes);
1302 
1303     /*
1304      * Set the threshold for the minimum number of free blocks in the
1305      * log to the maximum of what the caller needs, one quarter of the
1306      * log, and 256 blocks.
1307      */
1308     free_threshold = BTOBB(need_bytes);
1309     free_threshold = MAX(free_threshold, (log->l_logBBsize >> 2));
1310     free_threshold = MAX(free_threshold, 256);
1311     if (free_blocks < free_threshold) {
1312 	threshold_block = BLOCK_LSN(tail_lsn) + free_threshold;
1313 	threshold_cycle = CYCLE_LSN(tail_lsn);
1314 	if (threshold_block >= log->l_logBBsize) {
1315 	    threshold_block -= log->l_logBBsize;
1316 	    threshold_cycle += 1;
1317 	}
1318 	ASSIGN_ANY_LSN_HOST(threshold_lsn, threshold_cycle,
1319 		       threshold_block);
1320 
1321 	/* Don't pass in an lsn greater than the lsn of the last
1322 	 * log record known to be on disk.
1323 	 */
1324 	if (XFS_LSN_CMP(threshold_lsn, log->l_last_sync_lsn) > 0)
1325 	    threshold_lsn = log->l_last_sync_lsn;
1326     }
1327     GRANT_UNLOCK(log, s);
1328 
1329     /*
1330      * Get the transaction layer to kick the dirty buffers out to
1331      * disk asynchronously. No point in trying to do this if
1332      * the filesystem is shutting down.
1333      */
1334     if (threshold_lsn &&
1335 	!XLOG_FORCED_SHUTDOWN(log))
1336 	    xfs_trans_push_ail(mp, threshold_lsn);
1337 }	/* xlog_grant_push_ail */
1338 
1339 
1340 /*
1341  * Flush out the in-core log (iclog) to the on-disk log in an asynchronous
1342  * fashion.  Previously, we should have moved the current iclog
1343  * ptr in the log to point to the next available iclog.  This allows further
1344  * write to continue while this code syncs out an iclog ready to go.
1345  * Before an in-core log can be written out, the data section must be scanned
1346  * to save away the 1st word of each BBSIZE block into the header.  We replace
1347  * it with the current cycle count.  Each BBSIZE block is tagged with the
1348  * cycle count because there in an implicit assumption that drives will
1349  * guarantee that entire 512 byte blocks get written at once.  In other words,
1350  * we can't have part of a 512 byte block written and part not written.  By
1351  * tagging each block, we will know which blocks are valid when recovering
1352  * after an unclean shutdown.
1353  *
1354  * This routine is single threaded on the iclog.  No other thread can be in
1355  * this routine with the same iclog.  Changing contents of iclog can there-
1356  * fore be done without grabbing the state machine lock.  Updating the global
1357  * log will require grabbing the lock though.
1358  *
1359  * The entire log manager uses a logical block numbering scheme.  Only
1360  * log_sync (and then only bwrite()) know about the fact that the log may
1361  * not start with block zero on a given device.  The log block start offset
1362  * is added immediately before calling bwrite().
1363  */
1364 
1365 int
xlog_sync(xlog_t * log,xlog_in_core_t * iclog)1366 xlog_sync(xlog_t		*log,
1367 	  xlog_in_core_t	*iclog)
1368 {
1369 	xfs_caddr_t	dptr;		/* pointer to byte sized element */
1370 	xfs_buf_t	*bp;
1371 	int		i, ops;
1372 	uint		count;		/* byte count of bwrite */
1373 	uint		count_init;	/* initial count before roundup */
1374 	int		roundoff;       /* roundoff to BB or stripe */
1375 	int		split = 0;	/* split write into two regions */
1376 	int		error;
1377 	SPLDECL(s);
1378 	int		v2 = XFS_SB_VERSION_HASLOGV2(&log->l_mp->m_sb);
1379 
1380 	XFS_STATS_INC(xs_log_writes);
1381 	ASSERT(iclog->ic_refcnt == 0);
1382 
1383 	/* Add for LR header */
1384 	count_init = log->l_iclog_hsize + iclog->ic_offset;
1385 
1386 	/* Round out the log write size */
1387 	if (v2 && log->l_mp->m_sb.sb_logsunit > 1) {
1388 		/* we have a v2 stripe unit to use */
1389 		count = XLOG_LSUNITTOB(log, XLOG_BTOLSUNIT(log, count_init));
1390 	} else {
1391 		count = BBTOB(BTOBB(count_init));
1392 	}
1393 	roundoff = count - count_init;
1394 	ASSERT(roundoff >= 0);
1395 	ASSERT((v2 && log->l_mp->m_sb.sb_logsunit > 1 &&
1396                 roundoff < log->l_mp->m_sb.sb_logsunit)
1397 		||
1398 		(log->l_mp->m_sb.sb_logsunit <= 1 &&
1399 		 roundoff < BBTOB(1)));
1400 
1401 	/* move grant heads by roundoff in sync */
1402 	s = GRANT_LOCK(log);
1403 	xlog_grant_add_space(log, roundoff);
1404 	GRANT_UNLOCK(log, s);
1405 
1406 	/* put cycle number in every block */
1407 	xlog_pack_data(log, iclog, roundoff);
1408 
1409 	/* real byte length */
1410 	if (v2) {
1411 		INT_SET(iclog->ic_header.h_len,
1412 			ARCH_CONVERT,
1413 			iclog->ic_offset + roundoff);
1414 	} else {
1415 		INT_SET(iclog->ic_header.h_len, ARCH_CONVERT, iclog->ic_offset);
1416 	}
1417 
1418 	/* put ops count in correct order */
1419 	ops = iclog->ic_header.h_num_logops;
1420 	INT_SET(iclog->ic_header.h_num_logops, ARCH_CONVERT, ops);
1421 
1422 	bp	    = iclog->ic_bp;
1423 	XFS_BUF_PSEMA(bp, PRIBIO);
1424 	ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) == (unsigned long)1);
1425 	XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1426 	XFS_BUF_SET_ADDR(bp, BLOCK_LSN(INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT)));
1427 
1428 	XFS_STATS_ADD(xs_log_blocks, BTOBB(count));
1429 
1430 	/* Do we need to split this write into 2 parts? */
1431 	if (XFS_BUF_ADDR(bp) + BTOBB(count) > log->l_logBBsize) {
1432 		split = count - (BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp)));
1433 		count = BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp));
1434 		iclog->ic_bwritecnt = 2;	/* split into 2 writes */
1435 	} else {
1436 		iclog->ic_bwritecnt = 1;
1437 	}
1438 	XFS_BUF_SET_PTR(bp, (xfs_caddr_t) &(iclog->ic_header), count);
1439 	XFS_BUF_SET_FSPRIVATE(bp, iclog);	/* save for later */
1440 	XFS_BUF_BUSY(bp);
1441 	XFS_BUF_ASYNC(bp);
1442 	XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1443 	/*
1444 	 * Do an ordered write for the log block.
1445 	 *
1446 	 * It may not be needed to flush the first split block in the log wrap
1447 	 * case, but do it anyways to be safe -AK
1448 	 */
1449 	if (log->l_mp->m_flags & XFS_MOUNT_BARRIER)
1450 		XFS_BUF_ORDERED(bp);
1451 
1452 	ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1453 	ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1454 
1455 	xlog_verify_iclog(log, iclog, count, B_TRUE);
1456 
1457 	/* account for log which doesn't start at block #0 */
1458 	XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1459 	/*
1460 	 * Don't call xfs_bwrite here. We do log-syncs even when the filesystem
1461 	 * is shutting down.
1462 	 */
1463 	XFS_BUF_WRITE(bp);
1464 
1465 	if ((error = XFS_bwrite(bp))) {
1466 		xfs_ioerror_alert("xlog_sync", log->l_mp, bp,
1467 				  XFS_BUF_ADDR(bp));
1468 		return error;
1469 	}
1470 	if (split) {
1471 		bp		= iclog->ic_log->l_xbuf;
1472 		ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) ==
1473 							(unsigned long)1);
1474 		XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1475 		XFS_BUF_SET_ADDR(bp, 0);	     /* logical 0 */
1476 		XFS_BUF_SET_PTR(bp, (xfs_caddr_t)((__psint_t)&(iclog->ic_header)+
1477 					    (__psint_t)count), split);
1478 		XFS_BUF_SET_FSPRIVATE(bp, iclog);
1479 		XFS_BUF_BUSY(bp);
1480 		XFS_BUF_ASYNC(bp);
1481 		XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1482 		if (log->l_mp->m_flags & XFS_MOUNT_BARRIER)
1483 			XFS_BUF_ORDERED(bp);
1484 		dptr = XFS_BUF_PTR(bp);
1485 		/*
1486 		 * Bump the cycle numbers at the start of each block
1487 		 * since this part of the buffer is at the start of
1488 		 * a new cycle.  Watch out for the header magic number
1489 		 * case, though.
1490 		 */
1491 		for (i=0; i<split; i += BBSIZE) {
1492 			INT_MOD(*(uint *)dptr, ARCH_CONVERT, +1);
1493 			if (INT_GET(*(uint *)dptr, ARCH_CONVERT) == XLOG_HEADER_MAGIC_NUM)
1494 				INT_MOD(*(uint *)dptr, ARCH_CONVERT, +1);
1495 			dptr += BBSIZE;
1496 		}
1497 
1498 		ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1499 		ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1500 
1501 		/* account for internal log which doesn't start at block #0 */
1502 		XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1503 		XFS_BUF_WRITE(bp);
1504 		if ((error = XFS_bwrite(bp))) {
1505 			xfs_ioerror_alert("xlog_sync (split)", log->l_mp,
1506 					  bp, XFS_BUF_ADDR(bp));
1507 			return error;
1508 		}
1509 	}
1510 	return 0;
1511 }	/* xlog_sync */
1512 
1513 
1514 /*
1515  * Deallocate a log structure
1516  */
1517 void
xlog_dealloc_log(xlog_t * log)1518 xlog_dealloc_log(xlog_t *log)
1519 {
1520 	xlog_in_core_t	*iclog, *next_iclog;
1521 	xlog_ticket_t	*tic, *next_tic;
1522 	int		i;
1523 
1524 
1525 	iclog = log->l_iclog;
1526 	for (i=0; i<log->l_iclog_bufs; i++) {
1527 		sv_destroy(&iclog->ic_forcesema);
1528 		sv_destroy(&iclog->ic_writesema);
1529 		XFS_BUF_PSEMA(iclog->ic_bp, PRIBIO);
1530 		xfs_buf_free(iclog->ic_bp);
1531 #ifdef XFS_LOG_TRACE
1532 		if (iclog->ic_trace != NULL) {
1533 			ktrace_free(iclog->ic_trace);
1534 		}
1535 #endif
1536 		next_iclog = iclog->ic_next;
1537 		kmem_free(iclog->hic_data, log->l_iclog_size);
1538 		kmem_free(iclog, sizeof(xlog_in_core_t));
1539 		iclog = next_iclog;
1540 	}
1541 	freesema(&log->l_flushsema);
1542 	spinlock_destroy(&log->l_icloglock);
1543 	spinlock_destroy(&log->l_grant_lock);
1544 
1545 	/* XXXsup take a look at this again. */
1546 	if ((log->l_ticket_cnt != log->l_ticket_tcnt)  &&
1547 	    !XLOG_FORCED_SHUTDOWN(log)) {
1548 		xfs_fs_cmn_err(CE_WARN, log->l_mp,
1549 			"xlog_dealloc_log: (cnt: %d, total: %d)",
1550 			log->l_ticket_cnt, log->l_ticket_tcnt);
1551 		/* ASSERT(log->l_ticket_cnt == log->l_ticket_tcnt); */
1552 
1553 	} else {
1554 		tic = log->l_unmount_free;
1555 		while (tic) {
1556 			next_tic = tic->t_next;
1557 			kmem_free(tic, NBPP);
1558 			tic = next_tic;
1559 		}
1560 	}
1561 	XFS_BUF_PSEMA(log->l_xbuf, PRIBIO);
1562 	xfs_buf_free(log->l_xbuf);
1563 #ifdef XFS_LOG_TRACE
1564 	if (log->l_trace != NULL) {
1565 		ktrace_free(log->l_trace);
1566 	}
1567 	if (log->l_grant_trace != NULL) {
1568 		ktrace_free(log->l_grant_trace);
1569 	}
1570 #endif
1571 	log->l_mp->m_log = NULL;
1572 	kmem_free(log, sizeof(xlog_t));
1573 }	/* xlog_dealloc_log */
1574 
1575 /*
1576  * Update counters atomically now that memcpy is done.
1577  */
1578 /* ARGSUSED */
1579 static inline void
xlog_state_finish_copy(xlog_t * log,xlog_in_core_t * iclog,int record_cnt,int copy_bytes)1580 xlog_state_finish_copy(xlog_t		*log,
1581 		       xlog_in_core_t	*iclog,
1582 		       int		record_cnt,
1583 		       int		copy_bytes)
1584 {
1585 	SPLDECL(s);
1586 
1587 	s = LOG_LOCK(log);
1588 
1589 	iclog->ic_header.h_num_logops += record_cnt;
1590 	iclog->ic_offset += copy_bytes;
1591 
1592 	LOG_UNLOCK(log, s);
1593 }	/* xlog_state_finish_copy */
1594 
1595 
1596 
1597 
1598 /*
1599  * print out info relating to regions written which consume
1600  * the reservation
1601  */
1602 STATIC void
xlog_print_tic_res(xfs_mount_t * mp,xlog_ticket_t * ticket)1603 xlog_print_tic_res(xfs_mount_t *mp, xlog_ticket_t *ticket)
1604 {
1605 	uint i;
1606 	uint ophdr_spc = ticket->t_res_num_ophdrs * (uint)sizeof(xlog_op_header_t);
1607 
1608 	/* match with XLOG_REG_TYPE_* in xfs_log.h */
1609 	static char *res_type_str[XLOG_REG_TYPE_MAX] = {
1610 	    "bformat",
1611 	    "bchunk",
1612 	    "efi_format",
1613 	    "efd_format",
1614 	    "iformat",
1615 	    "icore",
1616 	    "iext",
1617 	    "ibroot",
1618 	    "ilocal",
1619 	    "iattr_ext",
1620 	    "iattr_broot",
1621 	    "iattr_local",
1622 	    "qformat",
1623 	    "dquot",
1624 	    "quotaoff",
1625 	    "LR header",
1626 	    "unmount",
1627 	    "commit",
1628 	    "trans header"
1629 	};
1630 	static char *trans_type_str[XFS_TRANS_TYPE_MAX] = {
1631 	    "SETATTR_NOT_SIZE",
1632 	    "SETATTR_SIZE",
1633 	    "INACTIVE",
1634 	    "CREATE",
1635 	    "CREATE_TRUNC",
1636 	    "TRUNCATE_FILE",
1637 	    "REMOVE",
1638 	    "LINK",
1639 	    "RENAME",
1640 	    "MKDIR",
1641 	    "RMDIR",
1642 	    "SYMLINK",
1643 	    "SET_DMATTRS",
1644 	    "GROWFS",
1645 	    "STRAT_WRITE",
1646 	    "DIOSTRAT",
1647 	    "WRITE_SYNC",
1648 	    "WRITEID",
1649 	    "ADDAFORK",
1650 	    "ATTRINVAL",
1651 	    "ATRUNCATE",
1652 	    "ATTR_SET",
1653 	    "ATTR_RM",
1654 	    "ATTR_FLAG",
1655 	    "CLEAR_AGI_BUCKET",
1656 	    "QM_SBCHANGE",
1657 	    "DUMMY1",
1658 	    "DUMMY2",
1659 	    "QM_QUOTAOFF",
1660 	    "QM_DQALLOC",
1661 	    "QM_SETQLIM",
1662 	    "QM_DQCLUSTER",
1663 	    "QM_QINOCREATE",
1664 	    "QM_QUOTAOFF_END",
1665 	    "SB_UNIT",
1666 	    "FSYNC_TS",
1667 	    "GROWFSRT_ALLOC",
1668 	    "GROWFSRT_ZERO",
1669 	    "GROWFSRT_FREE",
1670 	    "SWAPEXT"
1671 	};
1672 
1673 	xfs_fs_cmn_err(CE_WARN, mp,
1674 			"xfs_log_write: reservation summary:\n"
1675 			"  trans type  = %s (%u)\n"
1676 			"  unit res    = %d bytes\n"
1677 			"  current res = %d bytes\n"
1678 			"  total reg   = %u bytes (o/flow = %u bytes)\n"
1679 			"  ophdrs      = %u (ophdr space = %u bytes)\n"
1680 			"  ophdr + reg = %u bytes\n"
1681 			"  num regions = %u\n",
1682 			((ticket->t_trans_type <= 0 ||
1683 			  ticket->t_trans_type > XFS_TRANS_TYPE_MAX) ?
1684 			  "bad-trans-type" : trans_type_str[ticket->t_trans_type-1]),
1685 			ticket->t_trans_type,
1686 			ticket->t_unit_res,
1687 			ticket->t_curr_res,
1688 			ticket->t_res_arr_sum, ticket->t_res_o_flow,
1689 			ticket->t_res_num_ophdrs, ophdr_spc,
1690 			ticket->t_res_arr_sum +
1691 			ticket->t_res_o_flow + ophdr_spc,
1692 			ticket->t_res_num);
1693 
1694 	for (i = 0; i < ticket->t_res_num; i++) {
1695 		uint r_type = ticket->t_res_arr[i].r_type;
1696 		cmn_err(CE_WARN,
1697 			    "region[%u]: %s - %u bytes\n",
1698 			    i,
1699 			    ((r_type <= 0 || r_type > XLOG_REG_TYPE_MAX) ?
1700 			    "bad-rtype" : res_type_str[r_type-1]),
1701 			    ticket->t_res_arr[i].r_len);
1702 	}
1703 }
1704 
1705 /*
1706  * Write some region out to in-core log
1707  *
1708  * This will be called when writing externally provided regions or when
1709  * writing out a commit record for a given transaction.
1710  *
1711  * General algorithm:
1712  *	1. Find total length of this write.  This may include adding to the
1713  *		lengths passed in.
1714  *	2. Check whether we violate the tickets reservation.
1715  *	3. While writing to this iclog
1716  *	    A. Reserve as much space in this iclog as can get
1717  *	    B. If this is first write, save away start lsn
1718  *	    C. While writing this region:
1719  *		1. If first write of transaction, write start record
1720  *		2. Write log operation header (header per region)
1721  *		3. Find out if we can fit entire region into this iclog
1722  *		4. Potentially, verify destination memcpy ptr
1723  *		5. Memcpy (partial) region
1724  *		6. If partial copy, release iclog; otherwise, continue
1725  *			copying more regions into current iclog
1726  *	4. Mark want sync bit (in simulation mode)
1727  *	5. Release iclog for potential flush to on-disk log.
1728  *
1729  * ERRORS:
1730  * 1.	Panic if reservation is overrun.  This should never happen since
1731  *	reservation amounts are generated internal to the filesystem.
1732  * NOTES:
1733  * 1. Tickets are single threaded data structures.
1734  * 2. The XLOG_END_TRANS & XLOG_CONTINUE_TRANS flags are passed down to the
1735  *	syncing routine.  When a single log_write region needs to span
1736  *	multiple in-core logs, the XLOG_CONTINUE_TRANS bit should be set
1737  *	on all log operation writes which don't contain the end of the
1738  *	region.  The XLOG_END_TRANS bit is used for the in-core log
1739  *	operation which contains the end of the continued log_write region.
1740  * 3. When xlog_state_get_iclog_space() grabs the rest of the current iclog,
1741  *	we don't really know exactly how much space will be used.  As a result,
1742  *	we don't update ic_offset until the end when we know exactly how many
1743  *	bytes have been written out.
1744  */
1745 int
xlog_write(xfs_mount_t * mp,xfs_log_iovec_t reg[],int nentries,xfs_log_ticket_t tic,xfs_lsn_t * start_lsn,xlog_in_core_t ** commit_iclog,uint flags)1746 xlog_write(xfs_mount_t *	mp,
1747 	   xfs_log_iovec_t	reg[],
1748 	   int			nentries,
1749 	   xfs_log_ticket_t	tic,
1750 	   xfs_lsn_t		*start_lsn,
1751 	   xlog_in_core_t	**commit_iclog,
1752 	   uint			flags)
1753 {
1754     xlog_t	     *log    = mp->m_log;
1755     xlog_ticket_t    *ticket = (xlog_ticket_t *)tic;
1756     xlog_op_header_t *logop_head;    /* ptr to log operation header */
1757     xlog_in_core_t   *iclog = NULL;  /* ptr to current in-core log */
1758     __psint_t	     ptr;	     /* copy address into data region */
1759     int		     len;	     /* # xlog_write() bytes 2 still copy */
1760     int		     index;	     /* region index currently copying */
1761     int		     log_offset = 0; /* offset (from 0) into data region */
1762     int		     start_rec_copy; /* # bytes to copy for start record */
1763     int		     partial_copy;   /* did we split a region? */
1764     int		     partial_copy_len;/* # bytes copied if split region */
1765     int		     need_copy;	     /* # bytes need to memcpy this region */
1766     int		     copy_len;	     /* # bytes actually memcpy'ing */
1767     int		     copy_off;	     /* # bytes from entry start */
1768     int		     contwr;	     /* continued write of in-core log? */
1769     int		     error;
1770     int		     record_cnt = 0, data_cnt = 0;
1771 
1772     partial_copy_len = partial_copy = 0;
1773 
1774     /* Calculate potential maximum space.  Each region gets its own
1775      * xlog_op_header_t and may need to be double word aligned.
1776      */
1777     len = 0;
1778     if (ticket->t_flags & XLOG_TIC_INITED) {    /* acct for start rec of xact */
1779 	len += sizeof(xlog_op_header_t);
1780 	XLOG_TIC_ADD_OPHDR(ticket);
1781     }
1782 
1783     for (index = 0; index < nentries; index++) {
1784 	len += sizeof(xlog_op_header_t);	    /* each region gets >= 1 */
1785 	XLOG_TIC_ADD_OPHDR(ticket);
1786 	len += reg[index].i_len;
1787 	XLOG_TIC_ADD_REGION(ticket, reg[index].i_len, reg[index].i_type);
1788     }
1789     contwr = *start_lsn = 0;
1790 
1791     if (ticket->t_curr_res < len) {
1792 	xlog_print_tic_res(mp, ticket);
1793 #ifdef DEBUG
1794 	xlog_panic(
1795 		"xfs_log_write: reservation ran out. Need to up reservation");
1796 #else
1797 	/* Customer configurable panic */
1798 	xfs_cmn_err(XFS_PTAG_LOGRES, CE_ALERT, mp,
1799 		"xfs_log_write: reservation ran out. Need to up reservation");
1800 	/* If we did not panic, shutdown the filesystem */
1801 	xfs_force_shutdown(mp, XFS_CORRUPT_INCORE);
1802 #endif
1803     } else
1804 	ticket->t_curr_res -= len;
1805 
1806     for (index = 0; index < nentries; ) {
1807 	if ((error = xlog_state_get_iclog_space(log, len, &iclog, ticket,
1808 					       &contwr, &log_offset)))
1809 		return error;
1810 
1811 	ASSERT(log_offset <= iclog->ic_size - 1);
1812 	ptr = (__psint_t) ((char *)iclog->ic_datap+log_offset);
1813 
1814 	/* start_lsn is the first lsn written to. That's all we need. */
1815 	if (! *start_lsn)
1816 	    *start_lsn = INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT);
1817 
1818 	/* This loop writes out as many regions as can fit in the amount
1819 	 * of space which was allocated by xlog_state_get_iclog_space().
1820 	 */
1821 	while (index < nentries) {
1822 	    ASSERT(reg[index].i_len % sizeof(__int32_t) == 0);
1823 	    ASSERT((__psint_t)ptr % sizeof(__int32_t) == 0);
1824 	    start_rec_copy = 0;
1825 
1826 	    /* If first write for transaction, insert start record.
1827 	     * We can't be trying to commit if we are inited.  We can't
1828 	     * have any "partial_copy" if we are inited.
1829 	     */
1830 	    if (ticket->t_flags & XLOG_TIC_INITED) {
1831 		logop_head		= (xlog_op_header_t *)ptr;
1832 		INT_SET(logop_head->oh_tid, ARCH_CONVERT, ticket->t_tid);
1833 		logop_head->oh_clientid = ticket->t_clientid;
1834 		logop_head->oh_len	= 0;
1835 		logop_head->oh_flags    = XLOG_START_TRANS;
1836 		logop_head->oh_res2	= 0;
1837 		ticket->t_flags		&= ~XLOG_TIC_INITED;	/* clear bit */
1838 		record_cnt++;
1839 
1840 		start_rec_copy = sizeof(xlog_op_header_t);
1841 		xlog_write_adv_cnt(ptr, len, log_offset, start_rec_copy);
1842 	    }
1843 
1844 	    /* Copy log operation header directly into data section */
1845 	    logop_head			= (xlog_op_header_t *)ptr;
1846 	    INT_SET(logop_head->oh_tid, ARCH_CONVERT, ticket->t_tid);
1847 	    logop_head->oh_clientid	= ticket->t_clientid;
1848 	    logop_head->oh_res2		= 0;
1849 
1850 	    /* header copied directly */
1851 	    xlog_write_adv_cnt(ptr, len, log_offset, sizeof(xlog_op_header_t));
1852 
1853 	    /* are we copying a commit or unmount record? */
1854 	    logop_head->oh_flags = flags;
1855 
1856 	    /*
1857 	     * We've seen logs corrupted with bad transaction client
1858 	     * ids.  This makes sure that XFS doesn't generate them on.
1859 	     * Turn this into an EIO and shut down the filesystem.
1860 	     */
1861 	    switch (logop_head->oh_clientid)  {
1862 	    case XFS_TRANSACTION:
1863 	    case XFS_VOLUME:
1864 	    case XFS_LOG:
1865 		break;
1866 	    default:
1867 		xfs_fs_cmn_err(CE_WARN, mp,
1868 		    "Bad XFS transaction clientid 0x%x in ticket 0x%p",
1869 		    logop_head->oh_clientid, tic);
1870 		return XFS_ERROR(EIO);
1871 	    }
1872 
1873 	    /* Partial write last time? => (partial_copy != 0)
1874 	     * need_copy is the amount we'd like to copy if everything could
1875 	     * fit in the current memcpy.
1876 	     */
1877 	    need_copy =	reg[index].i_len - partial_copy_len;
1878 
1879 	    copy_off = partial_copy_len;
1880 	    if (need_copy <= iclog->ic_size - log_offset) { /*complete write */
1881 		INT_SET(logop_head->oh_len, ARCH_CONVERT, copy_len = need_copy);
1882 		if (partial_copy)
1883 		    logop_head->oh_flags|= (XLOG_END_TRANS|XLOG_WAS_CONT_TRANS);
1884 		partial_copy_len = partial_copy = 0;
1885 	    } else {					    /* partial write */
1886 		copy_len = iclog->ic_size - log_offset;
1887 		INT_SET(logop_head->oh_len, ARCH_CONVERT, copy_len);
1888 		logop_head->oh_flags |= XLOG_CONTINUE_TRANS;
1889 		if (partial_copy)
1890 			logop_head->oh_flags |= XLOG_WAS_CONT_TRANS;
1891 		partial_copy_len += copy_len;
1892 		partial_copy++;
1893 		len += sizeof(xlog_op_header_t); /* from splitting of region */
1894 		/* account for new log op header */
1895 		ticket->t_curr_res -= sizeof(xlog_op_header_t);
1896 		XLOG_TIC_ADD_OPHDR(ticket);
1897 	    }
1898 	    xlog_verify_dest_ptr(log, ptr);
1899 
1900 	    /* copy region */
1901 	    ASSERT(copy_len >= 0);
1902 	    memcpy((xfs_caddr_t)ptr, reg[index].i_addr + copy_off, copy_len);
1903 	    xlog_write_adv_cnt(ptr, len, log_offset, copy_len);
1904 
1905 	    /* make copy_len total bytes copied, including headers */
1906 	    copy_len += start_rec_copy + sizeof(xlog_op_header_t);
1907 	    record_cnt++;
1908 	    data_cnt += contwr ? copy_len : 0;
1909 	    if (partial_copy) {			/* copied partial region */
1910 		    /* already marked WANT_SYNC by xlog_state_get_iclog_space */
1911 		    xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1912 		    record_cnt = data_cnt = 0;
1913 		    if ((error = xlog_state_release_iclog(log, iclog)))
1914 			    return error;
1915 		    break;			/* don't increment index */
1916 	    } else {				/* copied entire region */
1917 		index++;
1918 		partial_copy_len = partial_copy = 0;
1919 
1920 		if (iclog->ic_size - log_offset <= sizeof(xlog_op_header_t)) {
1921 		    xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1922 		    record_cnt = data_cnt = 0;
1923 		    xlog_state_want_sync(log, iclog);
1924 		    if (commit_iclog) {
1925 			ASSERT(flags & XLOG_COMMIT_TRANS);
1926 			*commit_iclog = iclog;
1927 		    } else if ((error = xlog_state_release_iclog(log, iclog)))
1928 			   return error;
1929 		    if (index == nentries)
1930 			    return 0;		/* we are done */
1931 		    else
1932 			    break;
1933 		}
1934 	    } /* if (partial_copy) */
1935 	} /* while (index < nentries) */
1936     } /* for (index = 0; index < nentries; ) */
1937     ASSERT(len == 0);
1938 
1939     xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1940     if (commit_iclog) {
1941 	ASSERT(flags & XLOG_COMMIT_TRANS);
1942 	*commit_iclog = iclog;
1943 	return 0;
1944     }
1945     return xlog_state_release_iclog(log, iclog);
1946 }	/* xlog_write */
1947 
1948 
1949 /*****************************************************************************
1950  *
1951  *		State Machine functions
1952  *
1953  *****************************************************************************
1954  */
1955 
1956 /* Clean iclogs starting from the head.  This ordering must be
1957  * maintained, so an iclog doesn't become ACTIVE beyond one that
1958  * is SYNCING.  This is also required to maintain the notion that we use
1959  * a counting semaphore to hold off would be writers to the log when every
1960  * iclog is trying to sync to disk.
1961  *
1962  * State Change: DIRTY -> ACTIVE
1963  */
1964 STATIC void
xlog_state_clean_log(xlog_t * log)1965 xlog_state_clean_log(xlog_t *log)
1966 {
1967 	xlog_in_core_t	*iclog;
1968 	int changed = 0;
1969 
1970 	iclog = log->l_iclog;
1971 	do {
1972 		if (iclog->ic_state == XLOG_STATE_DIRTY) {
1973 			iclog->ic_state	= XLOG_STATE_ACTIVE;
1974 			iclog->ic_offset       = 0;
1975 			iclog->ic_callback	= NULL;   /* don't need to free */
1976 			/*
1977 			 * If the number of ops in this iclog indicate it just
1978 			 * contains the dummy transaction, we can
1979 			 * change state into IDLE (the second time around).
1980 			 * Otherwise we should change the state into
1981 			 * NEED a dummy.
1982 			 * We don't need to cover the dummy.
1983 			 */
1984 			if (!changed &&
1985 			   (INT_GET(iclog->ic_header.h_num_logops, ARCH_CONVERT) == XLOG_COVER_OPS)) {
1986 				changed = 1;
1987 			} else {
1988 				/*
1989 				 * We have two dirty iclogs so start over
1990 				 * This could also be num of ops indicates
1991 				 * this is not the dummy going out.
1992 				 */
1993 				changed = 2;
1994 			}
1995 			iclog->ic_header.h_num_logops = 0;
1996 			memset(iclog->ic_header.h_cycle_data, 0,
1997 			      sizeof(iclog->ic_header.h_cycle_data));
1998 			iclog->ic_header.h_lsn = 0;
1999 		} else if (iclog->ic_state == XLOG_STATE_ACTIVE)
2000 			/* do nothing */;
2001 		else
2002 			break;	/* stop cleaning */
2003 		iclog = iclog->ic_next;
2004 	} while (iclog != log->l_iclog);
2005 
2006 	/* log is locked when we are called */
2007 	/*
2008 	 * Change state for the dummy log recording.
2009 	 * We usually go to NEED. But we go to NEED2 if the changed indicates
2010 	 * we are done writing the dummy record.
2011 	 * If we are done with the second dummy recored (DONE2), then
2012 	 * we go to IDLE.
2013 	 */
2014 	if (changed) {
2015 		switch (log->l_covered_state) {
2016 		case XLOG_STATE_COVER_IDLE:
2017 		case XLOG_STATE_COVER_NEED:
2018 		case XLOG_STATE_COVER_NEED2:
2019 			log->l_covered_state = XLOG_STATE_COVER_NEED;
2020 			break;
2021 
2022 		case XLOG_STATE_COVER_DONE:
2023 			if (changed == 1)
2024 				log->l_covered_state = XLOG_STATE_COVER_NEED2;
2025 			else
2026 				log->l_covered_state = XLOG_STATE_COVER_NEED;
2027 			break;
2028 
2029 		case XLOG_STATE_COVER_DONE2:
2030 			if (changed == 1)
2031 				log->l_covered_state = XLOG_STATE_COVER_IDLE;
2032 			else
2033 				log->l_covered_state = XLOG_STATE_COVER_NEED;
2034 			break;
2035 
2036 		default:
2037 			ASSERT(0);
2038 		}
2039 	}
2040 }	/* xlog_state_clean_log */
2041 
2042 STATIC xfs_lsn_t
xlog_get_lowest_lsn(xlog_t * log)2043 xlog_get_lowest_lsn(
2044 	xlog_t		*log)
2045 {
2046 	xlog_in_core_t  *lsn_log;
2047 	xfs_lsn_t	lowest_lsn, lsn;
2048 
2049 	lsn_log = log->l_iclog;
2050 	lowest_lsn = 0;
2051 	do {
2052 	    if (!(lsn_log->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY))) {
2053 		lsn = INT_GET(lsn_log->ic_header.h_lsn, ARCH_CONVERT);
2054 		if ((lsn && !lowest_lsn) ||
2055 		    (XFS_LSN_CMP(lsn, lowest_lsn) < 0)) {
2056 			lowest_lsn = lsn;
2057 		}
2058 	    }
2059 	    lsn_log = lsn_log->ic_next;
2060 	} while (lsn_log != log->l_iclog);
2061 	return lowest_lsn;
2062 }
2063 
2064 
2065 STATIC void
xlog_state_do_callback(xlog_t * log,int aborted,xlog_in_core_t * ciclog)2066 xlog_state_do_callback(
2067 	xlog_t		*log,
2068 	int		aborted,
2069 	xlog_in_core_t	*ciclog)
2070 {
2071 	xlog_in_core_t	   *iclog;
2072 	xlog_in_core_t	   *first_iclog;	/* used to know when we've
2073 						 * processed all iclogs once */
2074 	xfs_log_callback_t *cb, *cb_next;
2075 	int		   flushcnt = 0;
2076 	xfs_lsn_t	   lowest_lsn;
2077 	int		   ioerrors;	/* counter: iclogs with errors */
2078 	int		   loopdidcallbacks; /* flag: inner loop did callbacks*/
2079 	int		   funcdidcallbacks; /* flag: function did callbacks */
2080 	int		   repeats;	/* for issuing console warnings if
2081 					 * looping too many times */
2082 	SPLDECL(s);
2083 
2084 	s = LOG_LOCK(log);
2085 	first_iclog = iclog = log->l_iclog;
2086 	ioerrors = 0;
2087 	funcdidcallbacks = 0;
2088 	repeats = 0;
2089 
2090 	do {
2091 		/*
2092 		 * Scan all iclogs starting with the one pointed to by the
2093 		 * log.  Reset this starting point each time the log is
2094 		 * unlocked (during callbacks).
2095 		 *
2096 		 * Keep looping through iclogs until one full pass is made
2097 		 * without running any callbacks.
2098 		 */
2099 		first_iclog = log->l_iclog;
2100 		iclog = log->l_iclog;
2101 		loopdidcallbacks = 0;
2102 		repeats++;
2103 
2104 		do {
2105 
2106 			/* skip all iclogs in the ACTIVE & DIRTY states */
2107 			if (iclog->ic_state &
2108 			    (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY)) {
2109 				iclog = iclog->ic_next;
2110 				continue;
2111 			}
2112 
2113 			/*
2114 			 * Between marking a filesystem SHUTDOWN and stopping
2115 			 * the log, we do flush all iclogs to disk (if there
2116 			 * wasn't a log I/O error). So, we do want things to
2117 			 * go smoothly in case of just a SHUTDOWN  w/o a
2118 			 * LOG_IO_ERROR.
2119 			 */
2120 			if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
2121 				/*
2122 				 * Can only perform callbacks in order.  Since
2123 				 * this iclog is not in the DONE_SYNC/
2124 				 * DO_CALLBACK state, we skip the rest and
2125 				 * just try to clean up.  If we set our iclog
2126 				 * to DO_CALLBACK, we will not process it when
2127 				 * we retry since a previous iclog is in the
2128 				 * CALLBACK and the state cannot change since
2129 				 * we are holding the LOG_LOCK.
2130 				 */
2131 				if (!(iclog->ic_state &
2132 					(XLOG_STATE_DONE_SYNC |
2133 						 XLOG_STATE_DO_CALLBACK))) {
2134 					if (ciclog && (ciclog->ic_state ==
2135 							XLOG_STATE_DONE_SYNC)) {
2136 						ciclog->ic_state = XLOG_STATE_DO_CALLBACK;
2137 					}
2138 					break;
2139 				}
2140 				/*
2141 				 * We now have an iclog that is in either the
2142 				 * DO_CALLBACK or DONE_SYNC states. The other
2143 				 * states (WANT_SYNC, SYNCING, or CALLBACK were
2144 				 * caught by the above if and are going to
2145 				 * clean (i.e. we aren't doing their callbacks)
2146 				 * see the above if.
2147 				 */
2148 
2149 				/*
2150 				 * We will do one more check here to see if we
2151 				 * have chased our tail around.
2152 				 */
2153 
2154 				lowest_lsn = xlog_get_lowest_lsn(log);
2155 				if (lowest_lsn && (
2156 					XFS_LSN_CMP(
2157 						lowest_lsn,
2158 						INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT)
2159 					)<0)) {
2160 					iclog = iclog->ic_next;
2161 					continue; /* Leave this iclog for
2162 						   * another thread */
2163 				}
2164 
2165 				iclog->ic_state = XLOG_STATE_CALLBACK;
2166 
2167 				LOG_UNLOCK(log, s);
2168 
2169 				/* l_last_sync_lsn field protected by
2170 				 * GRANT_LOCK. Don't worry about iclog's lsn.
2171 				 * No one else can be here except us.
2172 				 */
2173 				s = GRANT_LOCK(log);
2174 				ASSERT(XFS_LSN_CMP(
2175 						log->l_last_sync_lsn,
2176 						INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT)
2177 					)<=0);
2178 				log->l_last_sync_lsn = INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT);
2179 				GRANT_UNLOCK(log, s);
2180 
2181 				/*
2182 				 * Keep processing entries in the callback list
2183 				 * until we come around and it is empty.  We
2184 				 * need to atomically see that the list is
2185 				 * empty and change the state to DIRTY so that
2186 				 * we don't miss any more callbacks being added.
2187 				 */
2188 				s = LOG_LOCK(log);
2189 			} else {
2190 				ioerrors++;
2191 			}
2192 			cb = iclog->ic_callback;
2193 
2194 			while (cb != 0) {
2195 				iclog->ic_callback_tail = &(iclog->ic_callback);
2196 				iclog->ic_callback = NULL;
2197 				LOG_UNLOCK(log, s);
2198 
2199 				/* perform callbacks in the order given */
2200 				for (; cb != 0; cb = cb_next) {
2201 					cb_next = cb->cb_next;
2202 					cb->cb_func(cb->cb_arg, aborted);
2203 				}
2204 				s = LOG_LOCK(log);
2205 				cb = iclog->ic_callback;
2206 			}
2207 
2208 			loopdidcallbacks++;
2209 			funcdidcallbacks++;
2210 
2211 			ASSERT(iclog->ic_callback == 0);
2212 			if (!(iclog->ic_state & XLOG_STATE_IOERROR))
2213 				iclog->ic_state = XLOG_STATE_DIRTY;
2214 
2215 			/*
2216 			 * Transition from DIRTY to ACTIVE if applicable.
2217 			 * NOP if STATE_IOERROR.
2218 			 */
2219 			xlog_state_clean_log(log);
2220 
2221 			/* wake up threads waiting in xfs_log_force() */
2222 			sv_broadcast(&iclog->ic_forcesema);
2223 
2224 			iclog = iclog->ic_next;
2225 		} while (first_iclog != iclog);
2226 		if (repeats && (repeats % 10) == 0) {
2227 			xfs_fs_cmn_err(CE_WARN, log->l_mp,
2228 				"xlog_state_do_callback: looping %d", repeats);
2229 		}
2230 	} while (!ioerrors && loopdidcallbacks);
2231 
2232 	/*
2233 	 * make one last gasp attempt to see if iclogs are being left in
2234 	 * limbo..
2235 	 */
2236 #ifdef DEBUG
2237 	if (funcdidcallbacks) {
2238 		first_iclog = iclog = log->l_iclog;
2239 		do {
2240 			ASSERT(iclog->ic_state != XLOG_STATE_DO_CALLBACK);
2241 			/*
2242 			 * Terminate the loop if iclogs are found in states
2243 			 * which will cause other threads to clean up iclogs.
2244 			 *
2245 			 * SYNCING - i/o completion will go through logs
2246 			 * DONE_SYNC - interrupt thread should be waiting for
2247 			 *              LOG_LOCK
2248 			 * IOERROR - give up hope all ye who enter here
2249 			 */
2250 			if (iclog->ic_state == XLOG_STATE_WANT_SYNC ||
2251 			    iclog->ic_state == XLOG_STATE_SYNCING ||
2252 			    iclog->ic_state == XLOG_STATE_DONE_SYNC ||
2253 			    iclog->ic_state == XLOG_STATE_IOERROR )
2254 				break;
2255 			iclog = iclog->ic_next;
2256 		} while (first_iclog != iclog);
2257 	}
2258 #endif
2259 
2260 	if (log->l_iclog->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_IOERROR)) {
2261 		flushcnt = log->l_flushcnt;
2262 		log->l_flushcnt = 0;
2263 	}
2264 	LOG_UNLOCK(log, s);
2265 	while (flushcnt--)
2266 		vsema(&log->l_flushsema);
2267 }	/* xlog_state_do_callback */
2268 
2269 
2270 /*
2271  * Finish transitioning this iclog to the dirty state.
2272  *
2273  * Make sure that we completely execute this routine only when this is
2274  * the last call to the iclog.  There is a good chance that iclog flushes,
2275  * when we reach the end of the physical log, get turned into 2 separate
2276  * calls to bwrite.  Hence, one iclog flush could generate two calls to this
2277  * routine.  By using the reference count bwritecnt, we guarantee that only
2278  * the second completion goes through.
2279  *
2280  * Callbacks could take time, so they are done outside the scope of the
2281  * global state machine log lock.  Assume that the calls to cvsema won't
2282  * take a long time.  At least we know it won't sleep.
2283  */
2284 void
xlog_state_done_syncing(xlog_in_core_t * iclog,int aborted)2285 xlog_state_done_syncing(
2286 	xlog_in_core_t	*iclog,
2287 	int		aborted)
2288 {
2289 	xlog_t		   *log = iclog->ic_log;
2290 	SPLDECL(s);
2291 
2292 	s = LOG_LOCK(log);
2293 
2294 	ASSERT(iclog->ic_state == XLOG_STATE_SYNCING ||
2295 	       iclog->ic_state == XLOG_STATE_IOERROR);
2296 	ASSERT(iclog->ic_refcnt == 0);
2297 	ASSERT(iclog->ic_bwritecnt == 1 || iclog->ic_bwritecnt == 2);
2298 
2299 
2300 	/*
2301 	 * If we got an error, either on the first buffer, or in the case of
2302 	 * split log writes, on the second, we mark ALL iclogs STATE_IOERROR,
2303 	 * and none should ever be attempted to be written to disk
2304 	 * again.
2305 	 */
2306 	if (iclog->ic_state != XLOG_STATE_IOERROR) {
2307 		if (--iclog->ic_bwritecnt == 1) {
2308 			LOG_UNLOCK(log, s);
2309 			return;
2310 		}
2311 		iclog->ic_state = XLOG_STATE_DONE_SYNC;
2312 	}
2313 
2314 	/*
2315 	 * Someone could be sleeping prior to writing out the next
2316 	 * iclog buffer, we wake them all, one will get to do the
2317 	 * I/O, the others get to wait for the result.
2318 	 */
2319 	sv_broadcast(&iclog->ic_writesema);
2320 	LOG_UNLOCK(log, s);
2321 	xlog_state_do_callback(log, aborted, iclog);	/* also cleans log */
2322 }	/* xlog_state_done_syncing */
2323 
2324 
2325 /*
2326  * If the head of the in-core log ring is not (ACTIVE or DIRTY), then we must
2327  * sleep.  The flush semaphore is set to the number of in-core buffers and
2328  * decremented around disk syncing.  Therefore, if all buffers are syncing,
2329  * this semaphore will cause new writes to sleep until a sync completes.
2330  * Otherwise, this code just does p() followed by v().  This approximates
2331  * a sleep/wakeup except we can't race.
2332  *
2333  * The in-core logs are used in a circular fashion. They are not used
2334  * out-of-order even when an iclog past the head is free.
2335  *
2336  * return:
2337  *	* log_offset where xlog_write() can start writing into the in-core
2338  *		log's data space.
2339  *	* in-core log pointer to which xlog_write() should write.
2340  *	* boolean indicating this is a continued write to an in-core log.
2341  *		If this is the last write, then the in-core log's offset field
2342  *		needs to be incremented, depending on the amount of data which
2343  *		is copied.
2344  */
2345 int
xlog_state_get_iclog_space(xlog_t * log,int len,xlog_in_core_t ** iclogp,xlog_ticket_t * ticket,int * continued_write,int * logoffsetp)2346 xlog_state_get_iclog_space(xlog_t	  *log,
2347 			   int		  len,
2348 			   xlog_in_core_t **iclogp,
2349 			   xlog_ticket_t  *ticket,
2350 			   int		  *continued_write,
2351 			   int		  *logoffsetp)
2352 {
2353 	SPLDECL(s);
2354 	int		  log_offset;
2355 	xlog_rec_header_t *head;
2356 	xlog_in_core_t	  *iclog;
2357 	int		  error;
2358 
2359 restart:
2360 	s = LOG_LOCK(log);
2361 	if (XLOG_FORCED_SHUTDOWN(log)) {
2362 		LOG_UNLOCK(log, s);
2363 		return XFS_ERROR(EIO);
2364 	}
2365 
2366 	iclog = log->l_iclog;
2367 	if (! (iclog->ic_state == XLOG_STATE_ACTIVE)) {
2368 		log->l_flushcnt++;
2369 		LOG_UNLOCK(log, s);
2370 		xlog_trace_iclog(iclog, XLOG_TRACE_SLEEP_FLUSH);
2371 		XFS_STATS_INC(xs_log_noiclogs);
2372 		/* Ensure that log writes happen */
2373 		psema(&log->l_flushsema, PINOD);
2374 		goto restart;
2375 	}
2376 	ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
2377 	head = &iclog->ic_header;
2378 
2379 	iclog->ic_refcnt++;			/* prevents sync */
2380 	log_offset = iclog->ic_offset;
2381 
2382 	/* On the 1st write to an iclog, figure out lsn.  This works
2383 	 * if iclogs marked XLOG_STATE_WANT_SYNC always write out what they are
2384 	 * committing to.  If the offset is set, that's how many blocks
2385 	 * must be written.
2386 	 */
2387 	if (log_offset == 0) {
2388 		ticket->t_curr_res -= log->l_iclog_hsize;
2389 		XLOG_TIC_ADD_REGION(ticket,
2390 				    log->l_iclog_hsize,
2391 				    XLOG_REG_TYPE_LRHEADER);
2392 		INT_SET(head->h_cycle, ARCH_CONVERT, log->l_curr_cycle);
2393 		ASSIGN_LSN(head->h_lsn, log);
2394 		ASSERT(log->l_curr_block >= 0);
2395 	}
2396 
2397 	/* If there is enough room to write everything, then do it.  Otherwise,
2398 	 * claim the rest of the region and make sure the XLOG_STATE_WANT_SYNC
2399 	 * bit is on, so this will get flushed out.  Don't update ic_offset
2400 	 * until you know exactly how many bytes get copied.  Therefore, wait
2401 	 * until later to update ic_offset.
2402 	 *
2403 	 * xlog_write() algorithm assumes that at least 2 xlog_op_header_t's
2404 	 * can fit into remaining data section.
2405 	 */
2406 	if (iclog->ic_size - iclog->ic_offset < 2*sizeof(xlog_op_header_t)) {
2407 		xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2408 
2409 		/* If I'm the only one writing to this iclog, sync it to disk */
2410 		if (iclog->ic_refcnt == 1) {
2411 			LOG_UNLOCK(log, s);
2412 			if ((error = xlog_state_release_iclog(log, iclog)))
2413 				return error;
2414 		} else {
2415 			iclog->ic_refcnt--;
2416 			LOG_UNLOCK(log, s);
2417 		}
2418 		goto restart;
2419 	}
2420 
2421 	/* Do we have enough room to write the full amount in the remainder
2422 	 * of this iclog?  Or must we continue a write on the next iclog and
2423 	 * mark this iclog as completely taken?  In the case where we switch
2424 	 * iclogs (to mark it taken), this particular iclog will release/sync
2425 	 * to disk in xlog_write().
2426 	 */
2427 	if (len <= iclog->ic_size - iclog->ic_offset) {
2428 		*continued_write = 0;
2429 		iclog->ic_offset += len;
2430 	} else {
2431 		*continued_write = 1;
2432 		xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2433 	}
2434 	*iclogp = iclog;
2435 
2436 	ASSERT(iclog->ic_offset <= iclog->ic_size);
2437 	LOG_UNLOCK(log, s);
2438 
2439 	*logoffsetp = log_offset;
2440 	return 0;
2441 }	/* xlog_state_get_iclog_space */
2442 
2443 /*
2444  * Atomically get the log space required for a log ticket.
2445  *
2446  * Once a ticket gets put onto the reserveq, it will only return after
2447  * the needed reservation is satisfied.
2448  */
2449 STATIC int
xlog_grant_log_space(xlog_t * log,xlog_ticket_t * tic)2450 xlog_grant_log_space(xlog_t	   *log,
2451 		     xlog_ticket_t *tic)
2452 {
2453 	int		 free_bytes;
2454 	int		 need_bytes;
2455 	SPLDECL(s);
2456 #ifdef DEBUG
2457 	xfs_lsn_t	 tail_lsn;
2458 #endif
2459 
2460 
2461 #ifdef DEBUG
2462 	if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2463 		panic("grant Recovery problem");
2464 #endif
2465 
2466 	/* Is there space or do we need to sleep? */
2467 	s = GRANT_LOCK(log);
2468 	xlog_trace_loggrant(log, tic, "xlog_grant_log_space: enter");
2469 
2470 	/* something is already sleeping; insert new transaction at end */
2471 	if (log->l_reserve_headq) {
2472 		xlog_ins_ticketq(&log->l_reserve_headq, tic);
2473 		xlog_trace_loggrant(log, tic,
2474 				    "xlog_grant_log_space: sleep 1");
2475 		/*
2476 		 * Gotta check this before going to sleep, while we're
2477 		 * holding the grant lock.
2478 		 */
2479 		if (XLOG_FORCED_SHUTDOWN(log))
2480 			goto error_return;
2481 
2482 		XFS_STATS_INC(xs_sleep_logspace);
2483 		sv_wait(&tic->t_sema, PINOD|PLTWAIT, &log->l_grant_lock, s);
2484 		/*
2485 		 * If we got an error, and the filesystem is shutting down,
2486 		 * we'll catch it down below. So just continue...
2487 		 */
2488 		xlog_trace_loggrant(log, tic,
2489 				    "xlog_grant_log_space: wake 1");
2490 		s = GRANT_LOCK(log);
2491 	}
2492 	if (tic->t_flags & XFS_LOG_PERM_RESERV)
2493 		need_bytes = tic->t_unit_res*tic->t_ocnt;
2494 	else
2495 		need_bytes = tic->t_unit_res;
2496 
2497 redo:
2498 	if (XLOG_FORCED_SHUTDOWN(log))
2499 		goto error_return;
2500 
2501 	free_bytes = xlog_space_left(log, log->l_grant_reserve_cycle,
2502 				     log->l_grant_reserve_bytes);
2503 	if (free_bytes < need_bytes) {
2504 		if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2505 			xlog_ins_ticketq(&log->l_reserve_headq, tic);
2506 		xlog_trace_loggrant(log, tic,
2507 				    "xlog_grant_log_space: sleep 2");
2508 		XFS_STATS_INC(xs_sleep_logspace);
2509 		sv_wait(&tic->t_sema, PINOD|PLTWAIT, &log->l_grant_lock, s);
2510 
2511 		if (XLOG_FORCED_SHUTDOWN(log)) {
2512 			s = GRANT_LOCK(log);
2513 			goto error_return;
2514 		}
2515 
2516 		xlog_trace_loggrant(log, tic,
2517 				    "xlog_grant_log_space: wake 2");
2518 		xlog_grant_push_ail(log->l_mp, need_bytes);
2519 		s = GRANT_LOCK(log);
2520 		goto redo;
2521 	} else if (tic->t_flags & XLOG_TIC_IN_Q)
2522 		xlog_del_ticketq(&log->l_reserve_headq, tic);
2523 
2524 	/* we've got enough space */
2525 	xlog_grant_add_space(log, need_bytes);
2526 #ifdef DEBUG
2527 	tail_lsn = log->l_tail_lsn;
2528 	/*
2529 	 * Check to make sure the grant write head didn't just over lap the
2530 	 * tail.  If the cycles are the same, we can't be overlapping.
2531 	 * Otherwise, make sure that the cycles differ by exactly one and
2532 	 * check the byte count.
2533 	 */
2534 	if (CYCLE_LSN(tail_lsn) != log->l_grant_write_cycle) {
2535 		ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn));
2536 		ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn)));
2537 	}
2538 #endif
2539 	xlog_trace_loggrant(log, tic, "xlog_grant_log_space: exit");
2540 	xlog_verify_grant_head(log, 1);
2541 	GRANT_UNLOCK(log, s);
2542 	return 0;
2543 
2544  error_return:
2545 	if (tic->t_flags & XLOG_TIC_IN_Q)
2546 		xlog_del_ticketq(&log->l_reserve_headq, tic);
2547 	xlog_trace_loggrant(log, tic, "xlog_grant_log_space: err_ret");
2548 	/*
2549 	 * If we are failing, make sure the ticket doesn't have any
2550 	 * current reservations. We don't want to add this back when
2551 	 * the ticket/transaction gets cancelled.
2552 	 */
2553 	tic->t_curr_res = 0;
2554 	tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2555 	GRANT_UNLOCK(log, s);
2556 	return XFS_ERROR(EIO);
2557 }	/* xlog_grant_log_space */
2558 
2559 
2560 /*
2561  * Replenish the byte reservation required by moving the grant write head.
2562  *
2563  *
2564  */
2565 STATIC int
xlog_regrant_write_log_space(xlog_t * log,xlog_ticket_t * tic)2566 xlog_regrant_write_log_space(xlog_t	   *log,
2567 			     xlog_ticket_t *tic)
2568 {
2569 	SPLDECL(s);
2570 	int		free_bytes, need_bytes;
2571 	xlog_ticket_t	*ntic;
2572 #ifdef DEBUG
2573 	xfs_lsn_t	tail_lsn;
2574 #endif
2575 
2576 	tic->t_curr_res = tic->t_unit_res;
2577 	XLOG_TIC_RESET_RES(tic);
2578 
2579 	if (tic->t_cnt > 0)
2580 		return 0;
2581 
2582 #ifdef DEBUG
2583 	if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2584 		panic("regrant Recovery problem");
2585 #endif
2586 
2587 	s = GRANT_LOCK(log);
2588 	xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: enter");
2589 
2590 	if (XLOG_FORCED_SHUTDOWN(log))
2591 		goto error_return;
2592 
2593 	/* If there are other waiters on the queue then give them a
2594 	 * chance at logspace before us. Wake up the first waiters,
2595 	 * if we do not wake up all the waiters then go to sleep waiting
2596 	 * for more free space, otherwise try to get some space for
2597 	 * this transaction.
2598 	 */
2599 
2600 	if ((ntic = log->l_write_headq)) {
2601 		free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2602 					     log->l_grant_write_bytes);
2603 		do {
2604 			ASSERT(ntic->t_flags & XLOG_TIC_PERM_RESERV);
2605 
2606 			if (free_bytes < ntic->t_unit_res)
2607 				break;
2608 			free_bytes -= ntic->t_unit_res;
2609 			sv_signal(&ntic->t_sema);
2610 			ntic = ntic->t_next;
2611 		} while (ntic != log->l_write_headq);
2612 
2613 		if (ntic != log->l_write_headq) {
2614 			if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2615 				xlog_ins_ticketq(&log->l_write_headq, tic);
2616 
2617 			xlog_trace_loggrant(log, tic,
2618 				    "xlog_regrant_write_log_space: sleep 1");
2619 			XFS_STATS_INC(xs_sleep_logspace);
2620 			sv_wait(&tic->t_sema, PINOD|PLTWAIT,
2621 				&log->l_grant_lock, s);
2622 
2623 			/* If we're shutting down, this tic is already
2624 			 * off the queue */
2625 			if (XLOG_FORCED_SHUTDOWN(log)) {
2626 				s = GRANT_LOCK(log);
2627 				goto error_return;
2628 			}
2629 
2630 			xlog_trace_loggrant(log, tic,
2631 				    "xlog_regrant_write_log_space: wake 1");
2632 			xlog_grant_push_ail(log->l_mp, tic->t_unit_res);
2633 			s = GRANT_LOCK(log);
2634 		}
2635 	}
2636 
2637 	need_bytes = tic->t_unit_res;
2638 
2639 redo:
2640 	if (XLOG_FORCED_SHUTDOWN(log))
2641 		goto error_return;
2642 
2643 	free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2644 				     log->l_grant_write_bytes);
2645 	if (free_bytes < need_bytes) {
2646 		if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2647 			xlog_ins_ticketq(&log->l_write_headq, tic);
2648 		XFS_STATS_INC(xs_sleep_logspace);
2649 		sv_wait(&tic->t_sema, PINOD|PLTWAIT, &log->l_grant_lock, s);
2650 
2651 		/* If we're shutting down, this tic is already off the queue */
2652 		if (XLOG_FORCED_SHUTDOWN(log)) {
2653 			s = GRANT_LOCK(log);
2654 			goto error_return;
2655 		}
2656 
2657 		xlog_trace_loggrant(log, tic,
2658 				    "xlog_regrant_write_log_space: wake 2");
2659 		xlog_grant_push_ail(log->l_mp, need_bytes);
2660 		s = GRANT_LOCK(log);
2661 		goto redo;
2662 	} else if (tic->t_flags & XLOG_TIC_IN_Q)
2663 		xlog_del_ticketq(&log->l_write_headq, tic);
2664 
2665 	/* we've got enough space */
2666 	xlog_grant_add_space_write(log, need_bytes);
2667 #ifdef DEBUG
2668 	tail_lsn = log->l_tail_lsn;
2669 	if (CYCLE_LSN(tail_lsn) != log->l_grant_write_cycle) {
2670 		ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn));
2671 		ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn)));
2672 	}
2673 #endif
2674 
2675 	xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: exit");
2676 	xlog_verify_grant_head(log, 1);
2677 	GRANT_UNLOCK(log, s);
2678 	return 0;
2679 
2680 
2681  error_return:
2682 	if (tic->t_flags & XLOG_TIC_IN_Q)
2683 		xlog_del_ticketq(&log->l_reserve_headq, tic);
2684 	xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: err_ret");
2685 	/*
2686 	 * If we are failing, make sure the ticket doesn't have any
2687 	 * current reservations. We don't want to add this back when
2688 	 * the ticket/transaction gets cancelled.
2689 	 */
2690 	tic->t_curr_res = 0;
2691 	tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2692 	GRANT_UNLOCK(log, s);
2693 	return XFS_ERROR(EIO);
2694 }	/* xlog_regrant_write_log_space */
2695 
2696 
2697 /* The first cnt-1 times through here we don't need to
2698  * move the grant write head because the permanent
2699  * reservation has reserved cnt times the unit amount.
2700  * Release part of current permanent unit reservation and
2701  * reset current reservation to be one units worth.  Also
2702  * move grant reservation head forward.
2703  */
2704 STATIC void
xlog_regrant_reserve_log_space(xlog_t * log,xlog_ticket_t * ticket)2705 xlog_regrant_reserve_log_space(xlog_t	     *log,
2706 			       xlog_ticket_t *ticket)
2707 {
2708 	SPLDECL(s);
2709 
2710 	xlog_trace_loggrant(log, ticket,
2711 			    "xlog_regrant_reserve_log_space: enter");
2712 	if (ticket->t_cnt > 0)
2713 		ticket->t_cnt--;
2714 
2715 	s = GRANT_LOCK(log);
2716 	xlog_grant_sub_space(log, ticket->t_curr_res);
2717 	ticket->t_curr_res = ticket->t_unit_res;
2718 	XLOG_TIC_RESET_RES(ticket);
2719 	xlog_trace_loggrant(log, ticket,
2720 			    "xlog_regrant_reserve_log_space: sub current res");
2721 	xlog_verify_grant_head(log, 1);
2722 
2723 	/* just return if we still have some of the pre-reserved space */
2724 	if (ticket->t_cnt > 0) {
2725 		GRANT_UNLOCK(log, s);
2726 		return;
2727 	}
2728 
2729 	xlog_grant_add_space_reserve(log, ticket->t_unit_res);
2730 	xlog_trace_loggrant(log, ticket,
2731 			    "xlog_regrant_reserve_log_space: exit");
2732 	xlog_verify_grant_head(log, 0);
2733 	GRANT_UNLOCK(log, s);
2734 	ticket->t_curr_res = ticket->t_unit_res;
2735 	XLOG_TIC_RESET_RES(ticket);
2736 }	/* xlog_regrant_reserve_log_space */
2737 
2738 
2739 /*
2740  * Give back the space left from a reservation.
2741  *
2742  * All the information we need to make a correct determination of space left
2743  * is present.  For non-permanent reservations, things are quite easy.  The
2744  * count should have been decremented to zero.  We only need to deal with the
2745  * space remaining in the current reservation part of the ticket.  If the
2746  * ticket contains a permanent reservation, there may be left over space which
2747  * needs to be released.  A count of N means that N-1 refills of the current
2748  * reservation can be done before we need to ask for more space.  The first
2749  * one goes to fill up the first current reservation.  Once we run out of
2750  * space, the count will stay at zero and the only space remaining will be
2751  * in the current reservation field.
2752  */
2753 STATIC void
xlog_ungrant_log_space(xlog_t * log,xlog_ticket_t * ticket)2754 xlog_ungrant_log_space(xlog_t	     *log,
2755 		       xlog_ticket_t *ticket)
2756 {
2757 	SPLDECL(s);
2758 
2759 	if (ticket->t_cnt > 0)
2760 		ticket->t_cnt--;
2761 
2762 	s = GRANT_LOCK(log);
2763 	xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: enter");
2764 
2765 	xlog_grant_sub_space(log, ticket->t_curr_res);
2766 
2767 	xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: sub current");
2768 
2769 	/* If this is a permanent reservation ticket, we may be able to free
2770 	 * up more space based on the remaining count.
2771 	 */
2772 	if (ticket->t_cnt > 0) {
2773 		ASSERT(ticket->t_flags & XLOG_TIC_PERM_RESERV);
2774 		xlog_grant_sub_space(log, ticket->t_unit_res*ticket->t_cnt);
2775 	}
2776 
2777 	xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: exit");
2778 	xlog_verify_grant_head(log, 1);
2779 	GRANT_UNLOCK(log, s);
2780 	xfs_log_move_tail(log->l_mp, 1);
2781 }	/* xlog_ungrant_log_space */
2782 
2783 
2784 /*
2785  * Atomically put back used ticket.
2786  */
2787 void
xlog_state_put_ticket(xlog_t * log,xlog_ticket_t * tic)2788 xlog_state_put_ticket(xlog_t	    *log,
2789 		      xlog_ticket_t *tic)
2790 {
2791 	unsigned long s;
2792 
2793 	s = LOG_LOCK(log);
2794 	xlog_ticket_put(log, tic);
2795 	LOG_UNLOCK(log, s);
2796 }	/* xlog_state_put_ticket */
2797 
2798 /*
2799  * Flush iclog to disk if this is the last reference to the given iclog and
2800  * the WANT_SYNC bit is set.
2801  *
2802  * When this function is entered, the iclog is not necessarily in the
2803  * WANT_SYNC state.  It may be sitting around waiting to get filled.
2804  *
2805  *
2806  */
2807 int
xlog_state_release_iclog(xlog_t * log,xlog_in_core_t * iclog)2808 xlog_state_release_iclog(xlog_t		*log,
2809 			 xlog_in_core_t	*iclog)
2810 {
2811 	SPLDECL(s);
2812 	int		sync = 0;	/* do we sync? */
2813 
2814 	xlog_assign_tail_lsn(log->l_mp);
2815 
2816 	s = LOG_LOCK(log);
2817 
2818 	if (iclog->ic_state & XLOG_STATE_IOERROR) {
2819 		LOG_UNLOCK(log, s);
2820 		return XFS_ERROR(EIO);
2821 	}
2822 
2823 	ASSERT(iclog->ic_refcnt > 0);
2824 	ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE ||
2825 	       iclog->ic_state == XLOG_STATE_WANT_SYNC);
2826 
2827 	if (--iclog->ic_refcnt == 0 &&
2828 	    iclog->ic_state == XLOG_STATE_WANT_SYNC) {
2829 		sync++;
2830 		iclog->ic_state = XLOG_STATE_SYNCING;
2831 		INT_SET(iclog->ic_header.h_tail_lsn, ARCH_CONVERT, log->l_tail_lsn);
2832 		xlog_verify_tail_lsn(log, iclog, log->l_tail_lsn);
2833 		/* cycle incremented when incrementing curr_block */
2834 	}
2835 
2836 	LOG_UNLOCK(log, s);
2837 
2838 	/*
2839 	 * We let the log lock go, so it's possible that we hit a log I/O
2840 	 * error or some other SHUTDOWN condition that marks the iclog
2841 	 * as XLOG_STATE_IOERROR before the bwrite. However, we know that
2842 	 * this iclog has consistent data, so we ignore IOERROR
2843 	 * flags after this point.
2844 	 */
2845 	if (sync) {
2846 		return xlog_sync(log, iclog);
2847 	}
2848 	return 0;
2849 
2850 }	/* xlog_state_release_iclog */
2851 
2852 
2853 /*
2854  * This routine will mark the current iclog in the ring as WANT_SYNC
2855  * and move the current iclog pointer to the next iclog in the ring.
2856  * When this routine is called from xlog_state_get_iclog_space(), the
2857  * exact size of the iclog has not yet been determined.  All we know is
2858  * that every data block.  We have run out of space in this log record.
2859  */
2860 STATIC void
xlog_state_switch_iclogs(xlog_t * log,xlog_in_core_t * iclog,int eventual_size)2861 xlog_state_switch_iclogs(xlog_t		*log,
2862 			 xlog_in_core_t *iclog,
2863 			 int		eventual_size)
2864 {
2865 	ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
2866 	if (!eventual_size)
2867 		eventual_size = iclog->ic_offset;
2868 	iclog->ic_state = XLOG_STATE_WANT_SYNC;
2869 	INT_SET(iclog->ic_header.h_prev_block, ARCH_CONVERT, log->l_prev_block);
2870 	log->l_prev_block = log->l_curr_block;
2871 	log->l_prev_cycle = log->l_curr_cycle;
2872 
2873 	/* roll log?: ic_offset changed later */
2874 	log->l_curr_block += BTOBB(eventual_size)+BTOBB(log->l_iclog_hsize);
2875 
2876 	/* Round up to next log-sunit */
2877 	if (XFS_SB_VERSION_HASLOGV2(&log->l_mp->m_sb) &&
2878 	    log->l_mp->m_sb.sb_logsunit > 1) {
2879 		__uint32_t sunit_bb = BTOBB(log->l_mp->m_sb.sb_logsunit);
2880 		log->l_curr_block = roundup(log->l_curr_block, sunit_bb);
2881 	}
2882 
2883 	if (log->l_curr_block >= log->l_logBBsize) {
2884 		log->l_curr_cycle++;
2885 		if (log->l_curr_cycle == XLOG_HEADER_MAGIC_NUM)
2886 			log->l_curr_cycle++;
2887 		log->l_curr_block -= log->l_logBBsize;
2888 		ASSERT(log->l_curr_block >= 0);
2889 	}
2890 	ASSERT(iclog == log->l_iclog);
2891 	log->l_iclog = iclog->ic_next;
2892 }	/* xlog_state_switch_iclogs */
2893 
2894 
2895 /*
2896  * Write out all data in the in-core log as of this exact moment in time.
2897  *
2898  * Data may be written to the in-core log during this call.  However,
2899  * we don't guarantee this data will be written out.  A change from past
2900  * implementation means this routine will *not* write out zero length LRs.
2901  *
2902  * Basically, we try and perform an intelligent scan of the in-core logs.
2903  * If we determine there is no flushable data, we just return.  There is no
2904  * flushable data if:
2905  *
2906  *	1. the current iclog is active and has no data; the previous iclog
2907  *		is in the active or dirty state.
2908  *	2. the current iclog is drity, and the previous iclog is in the
2909  *		active or dirty state.
2910  *
2911  * We may sleep (call psema) if:
2912  *
2913  *	1. the current iclog is not in the active nor dirty state.
2914  *	2. the current iclog dirty, and the previous iclog is not in the
2915  *		active nor dirty state.
2916  *	3. the current iclog is active, and there is another thread writing
2917  *		to this particular iclog.
2918  *	4. a) the current iclog is active and has no other writers
2919  *	   b) when we return from flushing out this iclog, it is still
2920  *		not in the active nor dirty state.
2921  */
2922 STATIC int
xlog_state_sync_all(xlog_t * log,uint flags,int * log_flushed)2923 xlog_state_sync_all(xlog_t *log, uint flags, int *log_flushed)
2924 {
2925 	xlog_in_core_t	*iclog;
2926 	xfs_lsn_t	lsn;
2927 	SPLDECL(s);
2928 
2929 	s = LOG_LOCK(log);
2930 
2931 	iclog = log->l_iclog;
2932 	if (iclog->ic_state & XLOG_STATE_IOERROR) {
2933 		LOG_UNLOCK(log, s);
2934 		return XFS_ERROR(EIO);
2935 	}
2936 
2937 	/* If the head iclog is not active nor dirty, we just attach
2938 	 * ourselves to the head and go to sleep.
2939 	 */
2940 	if (iclog->ic_state == XLOG_STATE_ACTIVE ||
2941 	    iclog->ic_state == XLOG_STATE_DIRTY) {
2942 		/*
2943 		 * If the head is dirty or (active and empty), then
2944 		 * we need to look at the previous iclog.  If the previous
2945 		 * iclog is active or dirty we are done.  There is nothing
2946 		 * to sync out.  Otherwise, we attach ourselves to the
2947 		 * previous iclog and go to sleep.
2948 		 */
2949 		if (iclog->ic_state == XLOG_STATE_DIRTY ||
2950 		    (iclog->ic_refcnt == 0 && iclog->ic_offset == 0)) {
2951 			iclog = iclog->ic_prev;
2952 			if (iclog->ic_state == XLOG_STATE_ACTIVE ||
2953 			    iclog->ic_state == XLOG_STATE_DIRTY)
2954 				goto no_sleep;
2955 			else
2956 				goto maybe_sleep;
2957 		} else {
2958 			if (iclog->ic_refcnt == 0) {
2959 				/* We are the only one with access to this
2960 				 * iclog.  Flush it out now.  There should
2961 				 * be a roundoff of zero to show that someone
2962 				 * has already taken care of the roundoff from
2963 				 * the previous sync.
2964 				 */
2965 				iclog->ic_refcnt++;
2966 				lsn = INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT);
2967 				xlog_state_switch_iclogs(log, iclog, 0);
2968 				LOG_UNLOCK(log, s);
2969 
2970 				if (xlog_state_release_iclog(log, iclog))
2971 					return XFS_ERROR(EIO);
2972 				*log_flushed = 1;
2973 				s = LOG_LOCK(log);
2974 				if (INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT) == lsn &&
2975 				    iclog->ic_state != XLOG_STATE_DIRTY)
2976 					goto maybe_sleep;
2977 				else
2978 					goto no_sleep;
2979 			} else {
2980 				/* Someone else is writing to this iclog.
2981 				 * Use its call to flush out the data.  However,
2982 				 * the other thread may not force out this LR,
2983 				 * so we mark it WANT_SYNC.
2984 				 */
2985 				xlog_state_switch_iclogs(log, iclog, 0);
2986 				goto maybe_sleep;
2987 			}
2988 		}
2989 	}
2990 
2991 	/* By the time we come around again, the iclog could've been filled
2992 	 * which would give it another lsn.  If we have a new lsn, just
2993 	 * return because the relevant data has been flushed.
2994 	 */
2995 maybe_sleep:
2996 	if (flags & XFS_LOG_SYNC) {
2997 		/*
2998 		 * We must check if we're shutting down here, before
2999 		 * we wait, while we're holding the LOG_LOCK.
3000 		 * Then we check again after waking up, in case our
3001 		 * sleep was disturbed by a bad news.
3002 		 */
3003 		if (iclog->ic_state & XLOG_STATE_IOERROR) {
3004 			LOG_UNLOCK(log, s);
3005 			return XFS_ERROR(EIO);
3006 		}
3007 		XFS_STATS_INC(xs_log_force_sleep);
3008 		sv_wait(&iclog->ic_forcesema, PINOD, &log->l_icloglock, s);
3009 		/*
3010 		 * No need to grab the log lock here since we're
3011 		 * only deciding whether or not to return EIO
3012 		 * and the memory read should be atomic.
3013 		 */
3014 		if (iclog->ic_state & XLOG_STATE_IOERROR)
3015 			return XFS_ERROR(EIO);
3016 		*log_flushed = 1;
3017 
3018 	} else {
3019 
3020 no_sleep:
3021 		LOG_UNLOCK(log, s);
3022 	}
3023 	return 0;
3024 }	/* xlog_state_sync_all */
3025 
3026 
3027 /*
3028  * Used by code which implements synchronous log forces.
3029  *
3030  * Find in-core log with lsn.
3031  *	If it is in the DIRTY state, just return.
3032  *	If it is in the ACTIVE state, move the in-core log into the WANT_SYNC
3033  *		state and go to sleep or return.
3034  *	If it is in any other state, go to sleep or return.
3035  *
3036  * If filesystem activity goes to zero, the iclog will get flushed only by
3037  * bdflush().
3038  */
3039 int
xlog_state_sync(xlog_t * log,xfs_lsn_t lsn,uint flags,int * log_flushed)3040 xlog_state_sync(xlog_t	  *log,
3041 		xfs_lsn_t lsn,
3042 		uint	  flags,
3043 		int	  *log_flushed)
3044 {
3045     xlog_in_core_t	*iclog;
3046     int			already_slept = 0;
3047     SPLDECL(s);
3048 
3049 
3050 try_again:
3051     s = LOG_LOCK(log);
3052     iclog = log->l_iclog;
3053 
3054     if (iclog->ic_state & XLOG_STATE_IOERROR) {
3055 	    LOG_UNLOCK(log, s);
3056 	    return XFS_ERROR(EIO);
3057     }
3058 
3059     do {
3060 	if (INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT) != lsn) {
3061 	    iclog = iclog->ic_next;
3062 	    continue;
3063 	}
3064 
3065 	if (iclog->ic_state == XLOG_STATE_DIRTY) {
3066 		LOG_UNLOCK(log, s);
3067 		return 0;
3068 	}
3069 
3070 	if (iclog->ic_state == XLOG_STATE_ACTIVE) {
3071 		/*
3072 		 * We sleep here if we haven't already slept (e.g.
3073 		 * this is the first time we've looked at the correct
3074 		 * iclog buf) and the buffer before us is going to
3075 		 * be sync'ed. The reason for this is that if we
3076 		 * are doing sync transactions here, by waiting for
3077 		 * the previous I/O to complete, we can allow a few
3078 		 * more transactions into this iclog before we close
3079 		 * it down.
3080 		 *
3081 		 * Otherwise, we mark the buffer WANT_SYNC, and bump
3082 		 * up the refcnt so we can release the log (which drops
3083 		 * the ref count).  The state switch keeps new transaction
3084 		 * commits from using this buffer.  When the current commits
3085 		 * finish writing into the buffer, the refcount will drop to
3086 		 * zero and the buffer will go out then.
3087 		 */
3088 		if (!already_slept &&
3089 		    (iclog->ic_prev->ic_state & (XLOG_STATE_WANT_SYNC |
3090 						 XLOG_STATE_SYNCING))) {
3091 			ASSERT(!(iclog->ic_state & XLOG_STATE_IOERROR));
3092 			XFS_STATS_INC(xs_log_force_sleep);
3093 			sv_wait(&iclog->ic_prev->ic_writesema, PSWP,
3094 				&log->l_icloglock, s);
3095 			*log_flushed = 1;
3096 			already_slept = 1;
3097 			goto try_again;
3098 		} else {
3099 			iclog->ic_refcnt++;
3100 			xlog_state_switch_iclogs(log, iclog, 0);
3101 			LOG_UNLOCK(log, s);
3102 			if (xlog_state_release_iclog(log, iclog))
3103 				return XFS_ERROR(EIO);
3104 			*log_flushed = 1;
3105 			s = LOG_LOCK(log);
3106 		}
3107 	}
3108 
3109 	if ((flags & XFS_LOG_SYNC) && /* sleep */
3110 	    !(iclog->ic_state & (XLOG_STATE_ACTIVE | XLOG_STATE_DIRTY))) {
3111 
3112 		/*
3113 		 * Don't wait on the forcesema if we know that we've
3114 		 * gotten a log write error.
3115 		 */
3116 		if (iclog->ic_state & XLOG_STATE_IOERROR) {
3117 			LOG_UNLOCK(log, s);
3118 			return XFS_ERROR(EIO);
3119 		}
3120 		XFS_STATS_INC(xs_log_force_sleep);
3121 		sv_wait(&iclog->ic_forcesema, PSWP, &log->l_icloglock, s);
3122 		/*
3123 		 * No need to grab the log lock here since we're
3124 		 * only deciding whether or not to return EIO
3125 		 * and the memory read should be atomic.
3126 		 */
3127 		if (iclog->ic_state & XLOG_STATE_IOERROR)
3128 			return XFS_ERROR(EIO);
3129 		*log_flushed = 1;
3130 	} else {		/* just return */
3131 		LOG_UNLOCK(log, s);
3132 	}
3133 	return 0;
3134 
3135     } while (iclog != log->l_iclog);
3136 
3137     LOG_UNLOCK(log, s);
3138     return 0;
3139 }	/* xlog_state_sync */
3140 
3141 
3142 /*
3143  * Called when we want to mark the current iclog as being ready to sync to
3144  * disk.
3145  */
3146 void
xlog_state_want_sync(xlog_t * log,xlog_in_core_t * iclog)3147 xlog_state_want_sync(xlog_t *log, xlog_in_core_t *iclog)
3148 {
3149 	SPLDECL(s);
3150 
3151 	s = LOG_LOCK(log);
3152 
3153 	if (iclog->ic_state == XLOG_STATE_ACTIVE) {
3154 		xlog_state_switch_iclogs(log, iclog, 0);
3155 	} else {
3156 		ASSERT(iclog->ic_state &
3157 			(XLOG_STATE_WANT_SYNC|XLOG_STATE_IOERROR));
3158 	}
3159 
3160 	LOG_UNLOCK(log, s);
3161 }	/* xlog_state_want_sync */
3162 
3163 
3164 
3165 /*****************************************************************************
3166  *
3167  *		TICKET functions
3168  *
3169  *****************************************************************************
3170  */
3171 
3172 /*
3173  *	Algorithm doesn't take into account page size. ;-(
3174  */
3175 STATIC void
xlog_state_ticket_alloc(xlog_t * log)3176 xlog_state_ticket_alloc(xlog_t *log)
3177 {
3178 	xlog_ticket_t	*t_list;
3179 	xlog_ticket_t	*next;
3180 	xfs_caddr_t	buf;
3181 	uint		i = (NBPP / sizeof(xlog_ticket_t)) - 2;
3182 	SPLDECL(s);
3183 
3184 	/*
3185 	 * The kmem_zalloc may sleep, so we shouldn't be holding the
3186 	 * global lock.  XXXmiken: may want to use zone allocator.
3187 	 */
3188 	buf = (xfs_caddr_t) kmem_zalloc(NBPP, KM_SLEEP);
3189 
3190 	s = LOG_LOCK(log);
3191 
3192 	/* Attach 1st ticket to Q, so we can keep track of allocated memory */
3193 	t_list = (xlog_ticket_t *)buf;
3194 	t_list->t_next = log->l_unmount_free;
3195 	log->l_unmount_free = t_list++;
3196 	log->l_ticket_cnt++;
3197 	log->l_ticket_tcnt++;
3198 
3199 	/* Next ticket becomes first ticket attached to ticket free list */
3200 	if (log->l_freelist != NULL) {
3201 		ASSERT(log->l_tail != NULL);
3202 		log->l_tail->t_next = t_list;
3203 	} else {
3204 		log->l_freelist = t_list;
3205 	}
3206 	log->l_ticket_cnt++;
3207 	log->l_ticket_tcnt++;
3208 
3209 	/* Cycle through rest of alloc'ed memory, building up free Q */
3210 	for ( ; i > 0; i--) {
3211 		next = t_list + 1;
3212 		t_list->t_next = next;
3213 		t_list = next;
3214 		log->l_ticket_cnt++;
3215 		log->l_ticket_tcnt++;
3216 	}
3217 	t_list->t_next = NULL;
3218 	log->l_tail = t_list;
3219 	LOG_UNLOCK(log, s);
3220 }	/* xlog_state_ticket_alloc */
3221 
3222 
3223 /*
3224  * Put ticket into free list
3225  *
3226  * Assumption: log lock is held around this call.
3227  */
3228 STATIC void
xlog_ticket_put(xlog_t * log,xlog_ticket_t * ticket)3229 xlog_ticket_put(xlog_t		*log,
3230 		xlog_ticket_t	*ticket)
3231 {
3232 	sv_destroy(&ticket->t_sema);
3233 
3234 	/*
3235 	 * Don't think caching will make that much difference.  It's
3236 	 * more important to make debug easier.
3237 	 */
3238 #if 0
3239 	/* real code will want to use LIFO for caching */
3240 	ticket->t_next = log->l_freelist;
3241 	log->l_freelist = ticket;
3242 	/* no need to clear fields */
3243 #else
3244 	/* When we debug, it is easier if tickets are cycled */
3245 	ticket->t_next     = NULL;
3246 	if (log->l_tail != 0) {
3247 		log->l_tail->t_next = ticket;
3248 	} else {
3249 		ASSERT(log->l_freelist == 0);
3250 		log->l_freelist = ticket;
3251 	}
3252 	log->l_tail	    = ticket;
3253 #endif /* DEBUG */
3254 	log->l_ticket_cnt++;
3255 }	/* xlog_ticket_put */
3256 
3257 
3258 /*
3259  * Grab ticket off freelist or allocation some more
3260  */
3261 xlog_ticket_t *
xlog_ticket_get(xlog_t * log,int unit_bytes,int cnt,char client,uint xflags)3262 xlog_ticket_get(xlog_t		*log,
3263 		int		unit_bytes,
3264 		int		cnt,
3265 		char		client,
3266 		uint		xflags)
3267 {
3268 	xlog_ticket_t	*tic;
3269 	uint		num_headers;
3270 	SPLDECL(s);
3271 
3272  alloc:
3273 	if (log->l_freelist == NULL)
3274 		xlog_state_ticket_alloc(log);		/* potentially sleep */
3275 
3276 	s = LOG_LOCK(log);
3277 	if (log->l_freelist == NULL) {
3278 		LOG_UNLOCK(log, s);
3279 		goto alloc;
3280 	}
3281 	tic		= log->l_freelist;
3282 	log->l_freelist	= tic->t_next;
3283 	if (log->l_freelist == NULL)
3284 		log->l_tail = NULL;
3285 	log->l_ticket_cnt--;
3286 	LOG_UNLOCK(log, s);
3287 
3288 	/*
3289 	 * Permanent reservations have up to 'cnt'-1 active log operations
3290 	 * in the log.  A unit in this case is the amount of space for one
3291 	 * of these log operations.  Normal reservations have a cnt of 1
3292 	 * and their unit amount is the total amount of space required.
3293 	 *
3294 	 * The following lines of code account for non-transaction data
3295 	 * which occupy space in the on-disk log.
3296 	 *
3297 	 * Normal form of a transaction is:
3298 	 * <oph><trans-hdr><start-oph><reg1-oph><reg1><reg2-oph>...<commit-oph>
3299 	 * and then there are LR hdrs, split-recs and roundoff at end of syncs.
3300 	 *
3301 	 * We need to account for all the leadup data and trailer data
3302 	 * around the transaction data.
3303 	 * And then we need to account for the worst case in terms of using
3304 	 * more space.
3305 	 * The worst case will happen if:
3306 	 * - the placement of the transaction happens to be such that the
3307 	 *   roundoff is at its maximum
3308 	 * - the transaction data is synced before the commit record is synced
3309 	 *   i.e. <transaction-data><roundoff> | <commit-rec><roundoff>
3310 	 *   Therefore the commit record is in its own Log Record.
3311 	 *   This can happen as the commit record is called with its
3312 	 *   own region to xlog_write().
3313 	 *   This then means that in the worst case, roundoff can happen for
3314 	 *   the commit-rec as well.
3315 	 *   The commit-rec is smaller than padding in this scenario and so it is
3316 	 *   not added separately.
3317 	 */
3318 
3319 	/* for trans header */
3320 	unit_bytes += sizeof(xlog_op_header_t);
3321 	unit_bytes += sizeof(xfs_trans_header_t);
3322 
3323 	/* for start-rec */
3324 	unit_bytes += sizeof(xlog_op_header_t);
3325 
3326 	/* for LR headers */
3327 	num_headers = ((unit_bytes + log->l_iclog_size-1) >> log->l_iclog_size_log);
3328 	unit_bytes += log->l_iclog_hsize * num_headers;
3329 
3330 	/* for commit-rec LR header - note: padding will subsume the ophdr */
3331 	unit_bytes += log->l_iclog_hsize;
3332 
3333 	/* for split-recs - ophdrs added when data split over LRs */
3334 	unit_bytes += sizeof(xlog_op_header_t) * num_headers;
3335 
3336 	/* for roundoff padding for transaction data and one for commit record */
3337 	if (XFS_SB_VERSION_HASLOGV2(&log->l_mp->m_sb) &&
3338 	    log->l_mp->m_sb.sb_logsunit > 1) {
3339 		/* log su roundoff */
3340 		unit_bytes += 2*log->l_mp->m_sb.sb_logsunit;
3341 	} else {
3342 		/* BB roundoff */
3343 		unit_bytes += 2*BBSIZE;
3344         }
3345 
3346 	tic->t_unit_res		= unit_bytes;
3347 	tic->t_curr_res		= unit_bytes;
3348 	tic->t_cnt		= cnt;
3349 	tic->t_ocnt		= cnt;
3350 	tic->t_tid		= (xlog_tid_t)((__psint_t)tic & 0xffffffff);
3351 	tic->t_clientid		= client;
3352 	tic->t_flags		= XLOG_TIC_INITED;
3353 	tic->t_trans_type	= 0;
3354 	if (xflags & XFS_LOG_PERM_RESERV)
3355 		tic->t_flags |= XLOG_TIC_PERM_RESERV;
3356 	sv_init(&(tic->t_sema), SV_DEFAULT, "logtick");
3357 
3358 	XLOG_TIC_RESET_RES(tic);
3359 
3360 	return tic;
3361 }	/* xlog_ticket_get */
3362 
3363 
3364 /******************************************************************************
3365  *
3366  *		Log debug routines
3367  *
3368  ******************************************************************************
3369  */
3370 #if defined(DEBUG)
3371 /*
3372  * Make sure that the destination ptr is within the valid data region of
3373  * one of the iclogs.  This uses backup pointers stored in a different
3374  * part of the log in case we trash the log structure.
3375  */
3376 void
xlog_verify_dest_ptr(xlog_t * log,__psint_t ptr)3377 xlog_verify_dest_ptr(xlog_t     *log,
3378 		     __psint_t  ptr)
3379 {
3380 	int i;
3381 	int good_ptr = 0;
3382 
3383 	for (i=0; i < log->l_iclog_bufs; i++) {
3384 		if (ptr >= (__psint_t)log->l_iclog_bak[i] &&
3385 		    ptr <= (__psint_t)log->l_iclog_bak[i]+log->l_iclog_size)
3386 			good_ptr++;
3387 	}
3388 	if (! good_ptr)
3389 		xlog_panic("xlog_verify_dest_ptr: invalid ptr");
3390 }	/* xlog_verify_dest_ptr */
3391 
3392 STATIC void
xlog_verify_grant_head(xlog_t * log,int equals)3393 xlog_verify_grant_head(xlog_t *log, int equals)
3394 {
3395     if (log->l_grant_reserve_cycle == log->l_grant_write_cycle) {
3396 	if (equals)
3397 	    ASSERT(log->l_grant_reserve_bytes >= log->l_grant_write_bytes);
3398 	else
3399 	    ASSERT(log->l_grant_reserve_bytes > log->l_grant_write_bytes);
3400     } else {
3401 	ASSERT(log->l_grant_reserve_cycle-1 == log->l_grant_write_cycle);
3402 	ASSERT(log->l_grant_write_bytes >= log->l_grant_reserve_bytes);
3403     }
3404 }	/* xlog_verify_grant_head */
3405 
3406 /* check if it will fit */
3407 STATIC void
xlog_verify_tail_lsn(xlog_t * log,xlog_in_core_t * iclog,xfs_lsn_t tail_lsn)3408 xlog_verify_tail_lsn(xlog_t	    *log,
3409 		     xlog_in_core_t *iclog,
3410 		     xfs_lsn_t	    tail_lsn)
3411 {
3412     int blocks;
3413 
3414     if (CYCLE_LSN(tail_lsn) == log->l_prev_cycle) {
3415 	blocks =
3416 	    log->l_logBBsize - (log->l_prev_block - BLOCK_LSN(tail_lsn));
3417 	if (blocks < BTOBB(iclog->ic_offset)+BTOBB(log->l_iclog_hsize))
3418 	    xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3419     } else {
3420 	ASSERT(CYCLE_LSN(tail_lsn)+1 == log->l_prev_cycle);
3421 
3422 	if (BLOCK_LSN(tail_lsn) == log->l_prev_block)
3423 	    xlog_panic("xlog_verify_tail_lsn: tail wrapped");
3424 
3425 	blocks = BLOCK_LSN(tail_lsn) - log->l_prev_block;
3426 	if (blocks < BTOBB(iclog->ic_offset) + 1)
3427 	    xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3428     }
3429 }	/* xlog_verify_tail_lsn */
3430 
3431 /*
3432  * Perform a number of checks on the iclog before writing to disk.
3433  *
3434  * 1. Make sure the iclogs are still circular
3435  * 2. Make sure we have a good magic number
3436  * 3. Make sure we don't have magic numbers in the data
3437  * 4. Check fields of each log operation header for:
3438  *	A. Valid client identifier
3439  *	B. tid ptr value falls in valid ptr space (user space code)
3440  *	C. Length in log record header is correct according to the
3441  *		individual operation headers within record.
3442  * 5. When a bwrite will occur within 5 blocks of the front of the physical
3443  *	log, check the preceding blocks of the physical log to make sure all
3444  *	the cycle numbers agree with the current cycle number.
3445  */
3446 STATIC void
xlog_verify_iclog(xlog_t * log,xlog_in_core_t * iclog,int count,boolean_t syncing)3447 xlog_verify_iclog(xlog_t	 *log,
3448 		  xlog_in_core_t *iclog,
3449 		  int		 count,
3450 		  boolean_t	 syncing)
3451 {
3452 	xlog_op_header_t	*ophead;
3453 	xlog_in_core_t		*icptr;
3454 	xlog_in_core_2_t	*xhdr;
3455 	xfs_caddr_t		ptr;
3456 	xfs_caddr_t		base_ptr;
3457 	__psint_t		field_offset;
3458 	__uint8_t		clientid;
3459 	int			len, i, j, k, op_len;
3460 	int			idx;
3461 	SPLDECL(s);
3462 
3463 	/* check validity of iclog pointers */
3464 	s = LOG_LOCK(log);
3465 	icptr = log->l_iclog;
3466 	for (i=0; i < log->l_iclog_bufs; i++) {
3467 		if (icptr == 0)
3468 			xlog_panic("xlog_verify_iclog: invalid ptr");
3469 		icptr = icptr->ic_next;
3470 	}
3471 	if (icptr != log->l_iclog)
3472 		xlog_panic("xlog_verify_iclog: corrupt iclog ring");
3473 	LOG_UNLOCK(log, s);
3474 
3475 	/* check log magic numbers */
3476 	ptr = (xfs_caddr_t) &(iclog->ic_header);
3477 	if (INT_GET(*(uint *)ptr, ARCH_CONVERT) != XLOG_HEADER_MAGIC_NUM)
3478 		xlog_panic("xlog_verify_iclog: invalid magic num");
3479 
3480 	for (ptr += BBSIZE; ptr < ((xfs_caddr_t)&(iclog->ic_header))+count;
3481 	     ptr += BBSIZE) {
3482 		if (INT_GET(*(uint *)ptr, ARCH_CONVERT) == XLOG_HEADER_MAGIC_NUM)
3483 			xlog_panic("xlog_verify_iclog: unexpected magic num");
3484 	}
3485 
3486 	/* check fields */
3487 	len = INT_GET(iclog->ic_header.h_num_logops, ARCH_CONVERT);
3488 	ptr = iclog->ic_datap;
3489 	base_ptr = ptr;
3490 	ophead = (xlog_op_header_t *)ptr;
3491 	xhdr = (xlog_in_core_2_t *)&iclog->ic_header;
3492 	for (i = 0; i < len; i++) {
3493 		ophead = (xlog_op_header_t *)ptr;
3494 
3495 		/* clientid is only 1 byte */
3496 		field_offset = (__psint_t)
3497 			       ((xfs_caddr_t)&(ophead->oh_clientid) - base_ptr);
3498 		if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3499 			clientid = ophead->oh_clientid;
3500 		} else {
3501 			idx = BTOBBT((xfs_caddr_t)&(ophead->oh_clientid) - iclog->ic_datap);
3502 			if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3503 				j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3504 				k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3505 				clientid = GET_CLIENT_ID(xhdr[j].hic_xheader.xh_cycle_data[k], ARCH_CONVERT);
3506 			} else {
3507 				clientid = GET_CLIENT_ID(iclog->ic_header.h_cycle_data[idx], ARCH_CONVERT);
3508 			}
3509 		}
3510 		if (clientid != XFS_TRANSACTION && clientid != XFS_LOG)
3511 			cmn_err(CE_WARN, "xlog_verify_iclog: "
3512 				"invalid clientid %d op 0x%p offset 0x%lx",
3513 				clientid, ophead, (unsigned long)field_offset);
3514 
3515 		/* check length */
3516 		field_offset = (__psint_t)
3517 			       ((xfs_caddr_t)&(ophead->oh_len) - base_ptr);
3518 		if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3519 			op_len = INT_GET(ophead->oh_len, ARCH_CONVERT);
3520 		} else {
3521 			idx = BTOBBT((__psint_t)&ophead->oh_len -
3522 				    (__psint_t)iclog->ic_datap);
3523 			if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3524 				j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3525 				k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3526 				op_len = INT_GET(xhdr[j].hic_xheader.xh_cycle_data[k], ARCH_CONVERT);
3527 			} else {
3528 				op_len = INT_GET(iclog->ic_header.h_cycle_data[idx], ARCH_CONVERT);
3529 			}
3530 		}
3531 		ptr += sizeof(xlog_op_header_t) + op_len;
3532 	}
3533 }	/* xlog_verify_iclog */
3534 #endif
3535 
3536 /*
3537  * Mark all iclogs IOERROR. LOG_LOCK is held by the caller.
3538  */
3539 STATIC int
xlog_state_ioerror(xlog_t * log)3540 xlog_state_ioerror(
3541 	xlog_t	*log)
3542 {
3543 	xlog_in_core_t	*iclog, *ic;
3544 
3545 	iclog = log->l_iclog;
3546 	if (! (iclog->ic_state & XLOG_STATE_IOERROR)) {
3547 		/*
3548 		 * Mark all the incore logs IOERROR.
3549 		 * From now on, no log flushes will result.
3550 		 */
3551 		ic = iclog;
3552 		do {
3553 			ic->ic_state = XLOG_STATE_IOERROR;
3554 			ic = ic->ic_next;
3555 		} while (ic != iclog);
3556 		return 0;
3557 	}
3558 	/*
3559 	 * Return non-zero, if state transition has already happened.
3560 	 */
3561 	return 1;
3562 }
3563 
3564 /*
3565  * This is called from xfs_force_shutdown, when we're forcibly
3566  * shutting down the filesystem, typically because of an IO error.
3567  * Our main objectives here are to make sure that:
3568  *	a. the filesystem gets marked 'SHUTDOWN' for all interested
3569  *	   parties to find out, 'atomically'.
3570  *	b. those who're sleeping on log reservations, pinned objects and
3571  *	    other resources get woken up, and be told the bad news.
3572  *	c. nothing new gets queued up after (a) and (b) are done.
3573  *	d. if !logerror, flush the iclogs to disk, then seal them off
3574  *	   for business.
3575  */
3576 int
xfs_log_force_umount(struct xfs_mount * mp,int logerror)3577 xfs_log_force_umount(
3578 	struct xfs_mount	*mp,
3579 	int			logerror)
3580 {
3581 	xlog_ticket_t	*tic;
3582 	xlog_t		*log;
3583 	int		retval;
3584 	int		dummy;
3585 	SPLDECL(s);
3586 	SPLDECL(s2);
3587 
3588 	log = mp->m_log;
3589 
3590 	/*
3591 	 * If this happens during log recovery, don't worry about
3592 	 * locking; the log isn't open for business yet.
3593 	 */
3594 	if (!log ||
3595 	    log->l_flags & XLOG_ACTIVE_RECOVERY) {
3596 		mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3597 		XFS_BUF_DONE(mp->m_sb_bp);
3598 		return 0;
3599 	}
3600 
3601 	/*
3602 	 * Somebody could've already done the hard work for us.
3603 	 * No need to get locks for this.
3604 	 */
3605 	if (logerror && log->l_iclog->ic_state & XLOG_STATE_IOERROR) {
3606 		ASSERT(XLOG_FORCED_SHUTDOWN(log));
3607 		return 1;
3608 	}
3609 	retval = 0;
3610 	/*
3611 	 * We must hold both the GRANT lock and the LOG lock,
3612 	 * before we mark the filesystem SHUTDOWN and wake
3613 	 * everybody up to tell the bad news.
3614 	 */
3615 	s = GRANT_LOCK(log);
3616 	s2 = LOG_LOCK(log);
3617 	mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3618 	XFS_BUF_DONE(mp->m_sb_bp);
3619 	/*
3620 	 * This flag is sort of redundant because of the mount flag, but
3621 	 * it's good to maintain the separation between the log and the rest
3622 	 * of XFS.
3623 	 */
3624 	log->l_flags |= XLOG_IO_ERROR;
3625 
3626 	/*
3627 	 * If we hit a log error, we want to mark all the iclogs IOERROR
3628 	 * while we're still holding the loglock.
3629 	 */
3630 	if (logerror)
3631 		retval = xlog_state_ioerror(log);
3632 	LOG_UNLOCK(log, s2);
3633 
3634 	/*
3635 	 * We don't want anybody waiting for log reservations
3636 	 * after this. That means we have to wake up everybody
3637 	 * queued up on reserve_headq as well as write_headq.
3638 	 * In addition, we make sure in xlog_{re}grant_log_space
3639 	 * that we don't enqueue anything once the SHUTDOWN flag
3640 	 * is set, and this action is protected by the GRANTLOCK.
3641 	 */
3642 	if ((tic = log->l_reserve_headq)) {
3643 		do {
3644 			sv_signal(&tic->t_sema);
3645 			tic = tic->t_next;
3646 		} while (tic != log->l_reserve_headq);
3647 	}
3648 
3649 	if ((tic = log->l_write_headq)) {
3650 		do {
3651 			sv_signal(&tic->t_sema);
3652 			tic = tic->t_next;
3653 		} while (tic != log->l_write_headq);
3654 	}
3655 	GRANT_UNLOCK(log, s);
3656 
3657 	if (! (log->l_iclog->ic_state & XLOG_STATE_IOERROR)) {
3658 		ASSERT(!logerror);
3659 		/*
3660 		 * Force the incore logs to disk before shutting the
3661 		 * log down completely.
3662 		 */
3663 		xlog_state_sync_all(log, XFS_LOG_FORCE|XFS_LOG_SYNC, &dummy);
3664 		s2 = LOG_LOCK(log);
3665 		retval = xlog_state_ioerror(log);
3666 		LOG_UNLOCK(log, s2);
3667 	}
3668 	/*
3669 	 * Wake up everybody waiting on xfs_log_force.
3670 	 * Callback all log item committed functions as if the
3671 	 * log writes were completed.
3672 	 */
3673 	xlog_state_do_callback(log, XFS_LI_ABORTED, NULL);
3674 
3675 #ifdef XFSERRORDEBUG
3676 	{
3677 		xlog_in_core_t	*iclog;
3678 
3679 		s = LOG_LOCK(log);
3680 		iclog = log->l_iclog;
3681 		do {
3682 			ASSERT(iclog->ic_callback == 0);
3683 			iclog = iclog->ic_next;
3684 		} while (iclog != log->l_iclog);
3685 		LOG_UNLOCK(log, s);
3686 	}
3687 #endif
3688 	/* return non-zero if log IOERROR transition had already happened */
3689 	return retval;
3690 }
3691 
3692 STATIC int
xlog_iclogs_empty(xlog_t * log)3693 xlog_iclogs_empty(xlog_t *log)
3694 {
3695 	xlog_in_core_t	*iclog;
3696 
3697 	iclog = log->l_iclog;
3698 	do {
3699 		/* endianness does not matter here, zero is zero in
3700 		 * any language.
3701 		 */
3702 		if (iclog->ic_header.h_num_logops)
3703 			return 0;
3704 		iclog = iclog->ic_next;
3705 	} while (iclog != log->l_iclog);
3706 	return 1;
3707 }
3708 
3709