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