ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / fs / xfs / xfs_log.c
1 /*
2  * Copyright (c) 2000-2004 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                 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         vfs_t           *vfsp = XFS_MTOVFS(mp);
822
823         if (vfsp->vfs_super->s_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         xlog_t          *l;
945         int             aborted;
946
947         iclog = XFS_BUF_FSPRIVATE(bp, xlog_in_core_t *);
948         ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) == (unsigned long) 2);
949         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
950         aborted = 0;
951
952         /*
953          * Some versions of cpp barf on the recursive definition of
954          * ic_log -> hic_fields.ic_log and expand ic_log twice when
955          * it is passed through two macros.  Workaround broken cpp.
956          */
957         l = iclog->ic_log;
958
959         /*
960          * Race to shutdown the filesystem if we see an error.
961          */
962         if (XFS_TEST_ERROR((XFS_BUF_GETERROR(bp)), l->l_mp,
963                         XFS_ERRTAG_IODONE_IOERR, XFS_RANDOM_IODONE_IOERR)) {
964                 xfs_ioerror_alert("xlog_iodone", l->l_mp, bp, XFS_BUF_ADDR(bp));
965                 XFS_BUF_STALE(bp);
966                 xfs_force_shutdown(l->l_mp, XFS_LOG_IO_ERROR);
967                 /*
968                  * This flag will be propagated to the trans-committed
969                  * callback routines to let them know that the log-commit
970                  * didn't succeed.
971                  */
972                 aborted = XFS_LI_ABORTED;
973         } else if (iclog->ic_state & XLOG_STATE_IOERROR) {
974                 aborted = XFS_LI_ABORTED;
975         }
976         xlog_state_done_syncing(iclog, aborted);
977         if (!(XFS_BUF_ISASYNC(bp))) {
978                 /*
979                  * Corresponding psema() will be done in bwrite().  If we don't
980                  * vsema() here, panic.
981                  */
982                 XFS_BUF_V_IODONESEMA(bp);
983         }
984 }       /* xlog_iodone */
985
986 /*
987  * The bdstrat callback function for log bufs. This gives us a central
988  * place to trap bufs in case we get hit by a log I/O error and need to
989  * shutdown. Actually, in practice, even when we didn't get a log error,
990  * we transition the iclogs to IOERROR state *after* flushing all existing
991  * iclogs to disk. This is because we don't want anymore new transactions to be
992  * started or completed afterwards.
993  */
994 STATIC int
995 xlog_bdstrat_cb(struct xfs_buf *bp)
996 {
997         xlog_in_core_t *iclog;
998
999         iclog = XFS_BUF_FSPRIVATE(bp, xlog_in_core_t *);
1000
1001         if ((iclog->ic_state & XLOG_STATE_IOERROR) == 0) {
1002           /* note for irix bstrat will need  struct bdevsw passed
1003            * Fix the following macro if the code ever is merged
1004            */
1005             XFS_bdstrat(bp);
1006                 return 0;
1007         }
1008
1009         xfs_buftrace("XLOG__BDSTRAT IOERROR", bp);
1010         XFS_BUF_ERROR(bp, EIO);
1011         XFS_BUF_STALE(bp);
1012         xfs_biodone(bp);
1013         return (XFS_ERROR(EIO));
1014
1015
1016 }
1017
1018 /*
1019  * Return size of each in-core log record buffer.
1020  *
1021  * Low memory machines only get 2 16KB buffers.  We don't want to waste
1022  * memory here.  However, all other machines get at least 2 32KB buffers.
1023  * The number is hard coded because we don't care about the minimum
1024  * memory size, just 32MB systems.
1025  *
1026  * If the filesystem blocksize is too large, we may need to choose a
1027  * larger size since the directory code currently logs entire blocks.
1028  */
1029
1030 STATIC void
1031 xlog_get_iclog_buffer_size(xfs_mount_t  *mp,
1032                            xlog_t       *log)
1033 {
1034         int size;
1035         int xhdrs;
1036
1037 #if defined(DEBUG) || defined(XLOG_NOLOG)
1038         /*
1039          * When logbufs == 0, someone has disabled the log from the FSTAB
1040          * file.  This is not a documented feature.  We need to set xlog_debug
1041          * to zero (this deactivates the log) and set xlog_target to the
1042          * appropriate device.  Only one filesystem may be affected as such
1043          * since this is just a performance hack to test what we might be able
1044          * to get if the log were not present.
1045          */
1046         if (mp->m_logbufs == 0) {
1047                 xlog_debug = 0;
1048                 xlog_target = log->l_targ;
1049                 log->l_iclog_bufs = XLOG_MIN_ICLOGS;
1050         } else
1051 #endif
1052         {
1053                 /*
1054                  * This is the normal path.  If m_logbufs == -1, then the
1055                  * admin has chosen to use the system defaults for logbuffers.
1056                  */
1057                 if (mp->m_logbufs == -1) { 
1058                         if (xfs_physmem <= btoc(128*1024*1024)) { 
1059                                 log->l_iclog_bufs = XLOG_MIN_ICLOGS; 
1060                         } else if (xfs_physmem <= btoc(400*1024*1024)) { 
1061                                 log->l_iclog_bufs = XLOG_MED_ICLOGS; 
1062                         } else {
1063                                 /* 256K with 32K bufs */
1064                                 log->l_iclog_bufs = XLOG_MAX_ICLOGS;
1065                         }
1066                 } else
1067                         log->l_iclog_bufs = mp->m_logbufs;
1068
1069 #if defined(DEBUG) || defined(XLOG_NOLOG)
1070                 /* We are reactivating a filesystem after it was inactive */
1071                 if (log->l_targ == xlog_target) {
1072                         xlog_target = NULL;
1073                         xlog_debug = 1;
1074                 }
1075 #endif
1076         }
1077
1078         /*
1079          * Buffer size passed in from mount system call.
1080          */
1081         if (mp->m_logbsize != -1) {
1082                 size = log->l_iclog_size = mp->m_logbsize;
1083                 log->l_iclog_size_log = 0;
1084                 while (size != 1) {
1085                         log->l_iclog_size_log++;
1086                         size >>= 1;
1087                 }
1088
1089                 if (XFS_SB_VERSION_HASLOGV2(&mp->m_sb)) {
1090                         /* # headers = size / 32K
1091                          * one header holds cycles from 32K of data
1092                          */
1093
1094                         xhdrs = mp->m_logbsize / XLOG_HEADER_CYCLE_SIZE;
1095                         if (mp->m_logbsize % XLOG_HEADER_CYCLE_SIZE)
1096                                 xhdrs++;
1097                         log->l_iclog_hsize = xhdrs << BBSHIFT;
1098                         log->l_iclog_heads = xhdrs;
1099                 } else {
1100                         ASSERT(mp->m_logbsize <= XLOG_BIG_RECORD_BSIZE);
1101                         log->l_iclog_hsize = BBSIZE;
1102                         log->l_iclog_heads = 1;
1103                 }
1104                 return;
1105         }
1106
1107         /*
1108          * Special case machines that have less than 32MB of memory.
1109          * All machines with more memory use 32KB buffers.
1110          */
1111         if (xfs_physmem <= btoc(32*1024*1024)) {
1112                 /* Don't change; min configuration */
1113                 log->l_iclog_size = XLOG_RECORD_BSIZE;          /* 16k */
1114                 log->l_iclog_size_log = XLOG_RECORD_BSHIFT;
1115         } else {
1116                 log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;      /* 32k */
1117                 log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
1118         }
1119
1120         /* the default log size is 16k or 32k which is one header sector */
1121         log->l_iclog_hsize = BBSIZE;
1122         log->l_iclog_heads = 1;
1123
1124         /*
1125          * For 16KB, we use 3 32KB buffers.  For 32KB block sizes, we use
1126          * 4 32KB buffers.  For 64KB block sizes, we use 8 32KB buffers.
1127          */
1128         if (mp->m_sb.sb_blocksize >= 16*1024) {
1129                 log->l_iclog_size = XLOG_BIG_RECORD_BSIZE;
1130                 log->l_iclog_size_log = XLOG_BIG_RECORD_BSHIFT;
1131                 if (mp->m_logbufs == -1) {
1132                         switch (mp->m_sb.sb_blocksize) {
1133                             case 16*1024:                       /* 16 KB */
1134                                 log->l_iclog_bufs = 3;
1135                                 break;
1136                             case 32*1024:                       /* 32 KB */
1137                                 log->l_iclog_bufs = 4;
1138                                 break;
1139                             case 64*1024:                       /* 64 KB */
1140                                 log->l_iclog_bufs = 8;
1141                                 break;
1142                             default:
1143                                 xlog_panic("XFS: Invalid blocksize");
1144                                 break;
1145                         }
1146                 }
1147         }
1148 }       /* xlog_get_iclog_buffer_size */
1149
1150
1151 /*
1152  * This routine initializes some of the log structure for a given mount point.
1153  * Its primary purpose is to fill in enough, so recovery can occur.  However,
1154  * some other stuff may be filled in too.
1155  */
1156 STATIC xlog_t *
1157 xlog_alloc_log(xfs_mount_t      *mp,
1158                xfs_buftarg_t    *log_target,
1159                xfs_daddr_t      blk_offset,
1160                int              num_bblks)
1161 {
1162         xlog_t                  *log;
1163         xlog_rec_header_t       *head;
1164         xlog_in_core_t          **iclogp;
1165         xlog_in_core_t          *iclog, *prev_iclog=NULL;
1166         xfs_buf_t               *bp;
1167         int                     i;
1168         int                     iclogsize;
1169
1170         log = (xlog_t *)kmem_zalloc(sizeof(xlog_t), KM_SLEEP);
1171
1172         log->l_mp          = mp;
1173         log->l_targ        = log_target;
1174         log->l_logsize     = BBTOB(num_bblks);
1175         log->l_logBBstart  = blk_offset;
1176         log->l_logBBsize   = num_bblks;
1177         log->l_covered_state = XLOG_STATE_COVER_IDLE;
1178         log->l_flags       |= XLOG_ACTIVE_RECOVERY;
1179
1180         log->l_prev_block  = -1;
1181         ASSIGN_ANY_LSN(log->l_tail_lsn, 1, 0, ARCH_NOCONVERT);
1182         /* log->l_tail_lsn = 0x100000000LL; cycle = 1; current block = 0 */
1183         log->l_last_sync_lsn = log->l_tail_lsn;
1184         log->l_curr_cycle  = 1;     /* 0 is bad since this is initial value */
1185         log->l_grant_reserve_cycle = 1;
1186         log->l_grant_write_cycle = 1;
1187
1188         if (XFS_SB_VERSION_HASSECTOR(&mp->m_sb)) {
1189                 log->l_sectbb_log = mp->m_sb.sb_logsectlog - BBSHIFT;
1190                 ASSERT(log->l_sectbb_log <= mp->m_sectbb_log);
1191                 /* for larger sector sizes, must have v2 or external log */
1192                 ASSERT(log->l_sectbb_log == 0 ||
1193                         log->l_logBBstart == 0 ||
1194                         XFS_SB_VERSION_HASLOGV2(&mp->m_sb));
1195                 ASSERT(mp->m_sb.sb_logsectlog >= BBSHIFT);
1196         }
1197         log->l_sectbb_mask = (1 << log->l_sectbb_log) - 1;
1198
1199         xlog_get_iclog_buffer_size(mp, log);
1200
1201         bp = xfs_buf_get_empty(log->l_iclog_size, mp->m_logdev_targp);
1202         XFS_BUF_SET_IODONE_FUNC(bp, xlog_iodone);
1203         XFS_BUF_SET_BDSTRAT_FUNC(bp, xlog_bdstrat_cb);
1204         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)1);
1205         ASSERT(XFS_BUF_ISBUSY(bp));
1206         ASSERT(XFS_BUF_VALUSEMA(bp) <= 0);
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_zalloc(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                 sv_init(&iclog->ic_forcesema, SV_DEFAULT, "iclog-force");
1263                 sv_init(&iclog->ic_writesema, SV_DEFAULT, "iclog-write");
1264
1265                 iclogp = &iclog->ic_next;
1266         }
1267         *iclogp = log->l_iclog;                 /* complete ring */
1268         log->l_iclog->ic_prev = prev_iclog;     /* re-write 1st prev ptr */
1269
1270         return log;
1271 }       /* xlog_alloc_log */
1272
1273
1274 /*
1275  * Write out the commit record of a transaction associated with the given
1276  * ticket.  Return the lsn of the commit record.
1277  */
1278 STATIC int
1279 xlog_commit_record(xfs_mount_t  *mp,
1280                    xlog_ticket_t *ticket,
1281                    xlog_in_core_t **iclog,
1282                    xfs_lsn_t    *commitlsnp)
1283 {
1284         int             error;
1285         xfs_log_iovec_t reg[1];
1286
1287         reg[0].i_addr = 0;
1288         reg[0].i_len = 0;
1289
1290         ASSERT_ALWAYS(iclog);
1291         if ((error = xlog_write(mp, reg, 1, ticket, commitlsnp,
1292                                iclog, XLOG_COMMIT_TRANS))) {
1293                 xfs_force_shutdown(mp, XFS_LOG_IO_ERROR);
1294         }
1295         return (error);
1296 }       /* xlog_commit_record */
1297
1298
1299 /*
1300  * Push on the buffer cache code if we ever use more than 75% of the on-disk
1301  * log space.  This code pushes on the lsn which would supposedly free up
1302  * the 25% which we want to leave free.  We may need to adopt a policy which
1303  * pushes on an lsn which is further along in the log once we reach the high
1304  * water mark.  In this manner, we would be creating a low water mark.
1305  */
1306 void
1307 xlog_grant_push_ail(xfs_mount_t *mp,
1308                     int         need_bytes)
1309 {
1310     xlog_t      *log = mp->m_log;       /* pointer to the log */
1311     xfs_lsn_t   tail_lsn;               /* lsn of the log tail */
1312     xfs_lsn_t   threshold_lsn = 0;      /* lsn we'd like to be at */
1313     int         free_blocks;            /* free blocks left to write to */
1314     int         free_bytes;             /* free bytes left to write to */
1315     int         threshold_block;        /* block in lsn we'd like to be at */
1316     int         threshold_cycle;        /* lsn cycle we'd like to be at */
1317     int         free_threshold;
1318     SPLDECL(s);
1319
1320     ASSERT(BTOBB(need_bytes) < log->l_logBBsize);
1321
1322     s = GRANT_LOCK(log);
1323     free_bytes = xlog_space_left(log,
1324                                  log->l_grant_reserve_cycle,
1325                                  log->l_grant_reserve_bytes);
1326     tail_lsn = log->l_tail_lsn;
1327     free_blocks = BTOBBT(free_bytes);
1328
1329     /*
1330      * Set the threshold for the minimum number of free blocks in the
1331      * log to the maximum of what the caller needs, one quarter of the
1332      * log, and 256 blocks.
1333      */
1334     free_threshold = BTOBB(need_bytes);
1335     free_threshold = MAX(free_threshold, (log->l_logBBsize >> 2));
1336     free_threshold = MAX(free_threshold, 256);
1337     if (free_blocks < free_threshold) {
1338         threshold_block = BLOCK_LSN(tail_lsn, ARCH_NOCONVERT) + free_threshold;
1339         threshold_cycle = CYCLE_LSN(tail_lsn, ARCH_NOCONVERT);
1340         if (threshold_block >= log->l_logBBsize) {
1341             threshold_block -= log->l_logBBsize;
1342             threshold_cycle += 1;
1343         }
1344         ASSIGN_ANY_LSN(threshold_lsn, threshold_cycle,
1345                        threshold_block, ARCH_NOCONVERT);
1346
1347         /* Don't pass in an lsn greater than the lsn of the last
1348          * log record known to be on disk.
1349          */
1350         if (XFS_LSN_CMP_ARCH(threshold_lsn, log->l_last_sync_lsn, ARCH_NOCONVERT) > 0)
1351             threshold_lsn = log->l_last_sync_lsn;
1352     }
1353     GRANT_UNLOCK(log, s);
1354
1355     /*
1356      * Get the transaction layer to kick the dirty buffers out to
1357      * disk asynchronously. No point in trying to do this if
1358      * the filesystem is shutting down.
1359      */
1360     if (threshold_lsn &&
1361         !XLOG_FORCED_SHUTDOWN(log))
1362             xfs_trans_push_ail(mp, threshold_lsn);
1363 }       /* xlog_grant_push_ail */
1364
1365
1366 /*
1367  * Flush out the in-core log (iclog) to the on-disk log in a synchronous or
1368  * asynchronous fashion.  Previously, we should have moved the current iclog
1369  * ptr in the log to point to the next available iclog.  This allows further
1370  * write to continue while this code syncs out an iclog ready to go.
1371  * Before an in-core log can be written out, the data section must be scanned
1372  * to save away the 1st word of each BBSIZE block into the header.  We replace
1373  * it with the current cycle count.  Each BBSIZE block is tagged with the
1374  * cycle count because there in an implicit assumption that drives will
1375  * guarantee that entire 512 byte blocks get written at once.  In other words,
1376  * we can't have part of a 512 byte block written and part not written.  By
1377  * tagging each block, we will know which blocks are valid when recovering
1378  * after an unclean shutdown.
1379  *
1380  * This routine is single threaded on the iclog.  No other thread can be in
1381  * this routine with the same iclog.  Changing contents of iclog can there-
1382  * fore be done without grabbing the state machine lock.  Updating the global
1383  * log will require grabbing the lock though.
1384  *
1385  * The entire log manager uses a logical block numbering scheme.  Only
1386  * log_sync (and then only bwrite()) know about the fact that the log may
1387  * not start with block zero on a given device.  The log block start offset
1388  * is added immediately before calling bwrite().
1389  */
1390
1391 int
1392 xlog_sync(xlog_t                *log,
1393           xlog_in_core_t        *iclog)
1394 {
1395         xfs_caddr_t     dptr;           /* pointer to byte sized element */
1396         xfs_buf_t       *bp;
1397         int             i, ops;
1398         uint            count;          /* byte count of bwrite */
1399         uint            count_init;     /* initial count before roundup */
1400         int             split = 0;      /* split write into two regions */
1401         int             error;
1402
1403         XFS_STATS_INC(xs_log_writes);
1404         ASSERT(iclog->ic_refcnt == 0);
1405
1406         /* Add for LR header */
1407         count_init = log->l_iclog_hsize + iclog->ic_offset;
1408
1409         /* Round out the log write size */
1410         if (XFS_SB_VERSION_HASLOGV2(&log->l_mp->m_sb) &&
1411             log->l_mp->m_sb.sb_logsunit > 1) {
1412                 /* we have a v2 stripe unit to use */
1413                 count = XLOG_LSUNITTOB(log, XLOG_BTOLSUNIT(log, count_init));
1414         } else {
1415                 count = BBTOB(BTOBB(count_init));
1416         }
1417         iclog->ic_roundoff = count - count_init;
1418         log->l_roundoff += iclog->ic_roundoff;
1419
1420         xlog_pack_data(log, iclog);       /* put cycle number in every block */
1421
1422         /* real byte length */
1423         INT_SET(iclog->ic_header.h_len, 
1424                 ARCH_CONVERT,
1425                 iclog->ic_offset + iclog->ic_roundoff);
1426
1427         /* put ops count in correct order */
1428         ops = iclog->ic_header.h_num_logops;
1429         INT_SET(iclog->ic_header.h_num_logops, ARCH_CONVERT, ops);
1430
1431         bp          = iclog->ic_bp;
1432         ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) == (unsigned long)1);
1433         XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1434         XFS_BUF_SET_ADDR(bp, BLOCK_LSN(iclog->ic_header.h_lsn, ARCH_CONVERT));
1435
1436         XFS_STATS_ADD(xs_log_blocks, BTOBB(count));
1437
1438         /* Do we need to split this write into 2 parts? */
1439         if (XFS_BUF_ADDR(bp) + BTOBB(count) > log->l_logBBsize) {
1440                 split = count - (BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp)));
1441                 count = BBTOB(log->l_logBBsize - XFS_BUF_ADDR(bp));
1442                 iclog->ic_bwritecnt = 2;        /* split into 2 writes */
1443         } else {
1444                 iclog->ic_bwritecnt = 1;
1445         }
1446         XFS_BUF_SET_PTR(bp, (xfs_caddr_t) &(iclog->ic_header), count);
1447         XFS_BUF_SET_FSPRIVATE(bp, iclog);       /* save for later */
1448         XFS_BUF_BUSY(bp);
1449         XFS_BUF_ASYNC(bp);
1450         /*
1451          * Do a disk write cache flush for the log block.
1452          * This is a bit of a sledgehammer, it would be better
1453          * to use a tag barrier here that just prevents reordering.
1454          * It may not be needed to flush the first split block in the log wrap
1455          * case, but do it anyways to be safe -AK
1456          */
1457         if (!(log->l_mp->m_flags & XFS_MOUNT_NOLOGFLUSH))
1458                 XFS_BUF_FLUSH(bp);
1459
1460         ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1461         ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1462
1463         xlog_verify_iclog(log, iclog, count, B_TRUE);
1464
1465         /* account for log which doesn't start at block #0 */
1466         XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1467         /*
1468          * Don't call xfs_bwrite here. We do log-syncs even when the filesystem
1469          * is shutting down.
1470          */
1471         XFS_BUF_WRITE(bp);
1472
1473         if ((error = XFS_bwrite(bp))) {
1474                 xfs_ioerror_alert("xlog_sync", log->l_mp, bp,
1475                                   XFS_BUF_ADDR(bp));
1476                 return (error);
1477         }
1478         if (split) {
1479                 bp              = iclog->ic_log->l_xbuf;
1480                 ASSERT(XFS_BUF_FSPRIVATE2(bp, unsigned long) ==
1481                                                         (unsigned long)1);
1482                 XFS_BUF_SET_FSPRIVATE2(bp, (unsigned long)2);
1483                 XFS_BUF_SET_ADDR(bp, 0);             /* logical 0 */
1484                 XFS_BUF_SET_PTR(bp, (xfs_caddr_t)((__psint_t)&(iclog->ic_header)+
1485                                             (__psint_t)count), split);
1486                 XFS_BUF_SET_FSPRIVATE(bp, iclog);
1487                 XFS_BUF_BUSY(bp);
1488                 XFS_BUF_ASYNC(bp);
1489                 if (!(log->l_mp->m_flags & XFS_MOUNT_NOLOGFLUSH))
1490                         XFS_BUF_FLUSH(bp);
1491                 dptr = XFS_BUF_PTR(bp);
1492                 /*
1493                  * Bump the cycle numbers at the start of each block
1494                  * since this part of the buffer is at the start of
1495                  * a new cycle.  Watch out for the header magic number
1496                  * case, though.
1497                  */
1498                 for (i=0; i<split; i += BBSIZE) {
1499                         INT_MOD(*(uint *)dptr, ARCH_CONVERT, +1);
1500                         if (INT_GET(*(uint *)dptr, ARCH_CONVERT) == XLOG_HEADER_MAGIC_NUM)
1501                                 INT_MOD(*(uint *)dptr, ARCH_CONVERT, +1);
1502                         dptr += BBSIZE;
1503                 }
1504
1505                 ASSERT(XFS_BUF_ADDR(bp) <= log->l_logBBsize-1);
1506                 ASSERT(XFS_BUF_ADDR(bp) + BTOBB(count) <= log->l_logBBsize);
1507
1508                 /* account for internal log which does't start at block #0 */
1509                 XFS_BUF_SET_ADDR(bp, XFS_BUF_ADDR(bp) + log->l_logBBstart);
1510                 XFS_BUF_WRITE(bp);
1511                 if ((error = XFS_bwrite(bp))) {
1512                         xfs_ioerror_alert("xlog_sync (split)", log->l_mp,
1513                                           bp, XFS_BUF_ADDR(bp));
1514                         return (error);
1515                 }
1516         }
1517         return (0);
1518 }       /* xlog_sync */
1519
1520
1521 /*
1522  * Unallocate a log structure
1523  */
1524 void
1525 xlog_unalloc_log(xlog_t *log)
1526 {
1527         xlog_in_core_t  *iclog, *next_iclog;
1528         xlog_ticket_t   *tic, *next_tic;
1529         int             i;
1530
1531
1532         iclog = log->l_iclog;
1533         for (i=0; i<log->l_iclog_bufs; i++) {
1534                 sv_destroy(&iclog->ic_forcesema);
1535                 sv_destroy(&iclog->ic_writesema);
1536                 xfs_buf_free(iclog->ic_bp);
1537 #ifdef XFS_LOG_TRACE
1538                 if (iclog->ic_trace != NULL) {
1539                         ktrace_free(iclog->ic_trace);
1540                 }
1541 #endif
1542                 next_iclog = iclog->ic_next;
1543                 kmem_free(iclog->hic_data, log->l_iclog_size);
1544                 kmem_free(iclog, sizeof(xlog_in_core_t));
1545                 iclog = next_iclog;
1546         }
1547         freesema(&log->l_flushsema);
1548         spinlock_destroy(&log->l_icloglock);
1549         spinlock_destroy(&log->l_grant_lock);
1550
1551         /* XXXsup take a look at this again. */
1552         if ((log->l_ticket_cnt != log->l_ticket_tcnt)  &&
1553             !XLOG_FORCED_SHUTDOWN(log)) {
1554                 xfs_fs_cmn_err(CE_WARN, log->l_mp,
1555                         "xlog_unalloc_log: (cnt: %d, total: %d)",
1556                         log->l_ticket_cnt, log->l_ticket_tcnt);
1557                 /* ASSERT(log->l_ticket_cnt == log->l_ticket_tcnt); */
1558
1559         } else {
1560                 tic = log->l_unmount_free;
1561                 while (tic) {
1562                         next_tic = tic->t_next;
1563                         kmem_free(tic, NBPP);
1564                         tic = next_tic;
1565                 }
1566         }
1567         xfs_buf_free(log->l_xbuf);
1568 #ifdef XFS_LOG_TRACE
1569         if (log->l_trace != NULL) {
1570                 ktrace_free(log->l_trace);
1571         }
1572         if (log->l_grant_trace != NULL) {
1573                 ktrace_free(log->l_grant_trace);
1574         }
1575 #endif
1576         log->l_mp->m_log = NULL;
1577         kmem_free(log, sizeof(xlog_t));
1578 }       /* xlog_unalloc_log */
1579
1580 /*
1581  * Update counters atomically now that memcpy is done.
1582  */
1583 /* ARGSUSED */
1584 static inline void
1585 xlog_state_finish_copy(xlog_t           *log,
1586                        xlog_in_core_t   *iclog,
1587                        int              record_cnt,
1588                        int              copy_bytes)
1589 {
1590         SPLDECL(s);
1591
1592         s = LOG_LOCK(log);
1593
1594         iclog->ic_header.h_num_logops += record_cnt;
1595         iclog->ic_offset += copy_bytes;
1596
1597         LOG_UNLOCK(log, s);
1598 }       /* xlog_state_finish_copy */
1599
1600
1601
1602
1603 /*
1604  * Write some region out to in-core log
1605  *
1606  * This will be called when writing externally provided regions or when
1607  * writing out a commit record for a given transaction.
1608  *
1609  * General algorithm:
1610  *      1. Find total length of this write.  This may include adding to the
1611  *              lengths passed in.
1612  *      2. Check whether we violate the tickets reservation.
1613  *      3. While writing to this iclog
1614  *          A. Reserve as much space in this iclog as can get
1615  *          B. If this is first write, save away start lsn
1616  *          C. While writing this region:
1617  *              1. If first write of transaction, write start record
1618  *              2. Write log operation header (header per region)
1619  *              3. Find out if we can fit entire region into this iclog
1620  *              4. Potentially, verify destination memcpy ptr
1621  *              5. Memcpy (partial) region
1622  *              6. If partial copy, release iclog; otherwise, continue
1623  *                      copying more regions into current iclog
1624  *      4. Mark want sync bit (in simulation mode)
1625  *      5. Release iclog for potential flush to on-disk log.
1626  *
1627  * ERRORS:
1628  * 1.   Panic if reservation is overrun.  This should never happen since
1629  *      reservation amounts are generated internal to the filesystem.
1630  * NOTES:
1631  * 1. Tickets are single threaded data structures.
1632  * 2. The XLOG_END_TRANS & XLOG_CONTINUE_TRANS flags are passed down to the
1633  *      syncing routine.  When a single log_write region needs to span
1634  *      multiple in-core logs, the XLOG_CONTINUE_TRANS bit should be set
1635  *      on all log operation writes which don't contain the end of the
1636  *      region.  The XLOG_END_TRANS bit is used for the in-core log
1637  *      operation which contains the end of the continued log_write region.
1638  * 3. When xlog_state_get_iclog_space() grabs the rest of the current iclog,
1639  *      we don't really know exactly how much space will be used.  As a result,
1640  *      we don't update ic_offset until the end when we know exactly how many
1641  *      bytes have been written out.
1642  */
1643 int
1644 xlog_write(xfs_mount_t *        mp,
1645            xfs_log_iovec_t      reg[],
1646            int                  nentries,
1647            xfs_log_ticket_t     tic,
1648            xfs_lsn_t            *start_lsn,
1649            xlog_in_core_t       **commit_iclog,
1650            uint                 flags)
1651 {
1652     xlog_t           *log    = mp->m_log;
1653     xlog_ticket_t    *ticket = (xlog_ticket_t *)tic;
1654     xlog_op_header_t *logop_head;    /* ptr to log operation header */
1655     xlog_in_core_t   *iclog;         /* ptr to current in-core log */
1656     __psint_t        ptr;            /* copy address into data region */
1657     int              len;            /* # xlog_write() bytes 2 still copy */
1658     int              index;          /* region index currently copying */
1659     int              log_offset;     /* offset (from 0) into data region */
1660     int              start_rec_copy; /* # bytes to copy for start record */
1661     int              partial_copy;   /* did we split a region? */
1662     int              partial_copy_len;/* # bytes copied if split region */
1663     int              need_copy;      /* # bytes need to memcpy this region */
1664     int              copy_len;       /* # bytes actually memcpy'ing */
1665     int              copy_off;       /* # bytes from entry start */
1666     int              contwr;         /* continued write of in-core log? */
1667     int              firstwr = 0;    /* first write of transaction */
1668     int              error;
1669     int              record_cnt = 0, data_cnt = 0;
1670
1671     partial_copy_len = partial_copy = 0;
1672
1673     /* Calculate potential maximum space.  Each region gets its own
1674      * xlog_op_header_t and may need to be double word aligned.
1675      */
1676     len = 0;
1677     if (ticket->t_flags & XLOG_TIC_INITED)     /* acct for start rec of xact */
1678         len += sizeof(xlog_op_header_t);
1679
1680     for (index = 0; index < nentries; index++) {
1681         len += sizeof(xlog_op_header_t);            /* each region gets >= 1 */
1682         len += reg[index].i_len;
1683     }
1684     contwr = *start_lsn = 0;
1685
1686     if (ticket->t_curr_res < len) {
1687 #ifdef DEBUG
1688         xlog_panic(
1689                 "xfs_log_write: reservation ran out. Need to up reservation");
1690 #else
1691         /* Customer configurable panic */
1692         xfs_cmn_err(XFS_PTAG_LOGRES, CE_ALERT, mp,
1693                 "xfs_log_write: reservation ran out. Need to up reservation");
1694         /* If we did not panic, shutdown the filesystem */
1695         xfs_force_shutdown(mp, XFS_CORRUPT_INCORE);
1696 #endif
1697     } else
1698         ticket->t_curr_res -= len;
1699
1700     for (index = 0; index < nentries; ) {
1701         if ((error = xlog_state_get_iclog_space(log, len, &iclog, ticket,
1702                                                &contwr, &log_offset)))
1703                 return (error);
1704
1705         ASSERT(log_offset <= iclog->ic_size - 1);
1706         ptr = (__psint_t) ((char *)iclog->ic_datap+log_offset);
1707
1708         /* start_lsn is the first lsn written to. That's all we need. */
1709         if (! *start_lsn)
1710             *start_lsn = INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT);
1711
1712         /* This loop writes out as many regions as can fit in the amount
1713          * of space which was allocated by xlog_state_get_iclog_space().
1714          */
1715         while (index < nentries) {
1716             ASSERT(reg[index].i_len % sizeof(__int32_t) == 0);
1717             ASSERT((__psint_t)ptr % sizeof(__int32_t) == 0);
1718             start_rec_copy = 0;
1719
1720             /* If first write for transaction, insert start record.
1721              * We can't be trying to commit if we are inited.  We can't
1722              * have any "partial_copy" if we are inited.
1723              */
1724             if (ticket->t_flags & XLOG_TIC_INITED) {
1725                 logop_head              = (xlog_op_header_t *)ptr;
1726                 INT_SET(logop_head->oh_tid, ARCH_CONVERT, ticket->t_tid);
1727                 logop_head->oh_clientid = ticket->t_clientid;
1728                 INT_ZERO(logop_head->oh_len, ARCH_CONVERT);
1729                 logop_head->oh_flags    = XLOG_START_TRANS;
1730                 INT_ZERO(logop_head->oh_res2, ARCH_CONVERT);
1731                 ticket->t_flags         &= ~XLOG_TIC_INITED;    /* clear bit */
1732                 firstwr = 1;                      /* increment log ops below */
1733                 record_cnt++;
1734
1735                 start_rec_copy = sizeof(xlog_op_header_t);
1736                 xlog_write_adv_cnt(ptr, len, log_offset, start_rec_copy);
1737             }
1738
1739             /* Copy log operation header directly into data section */
1740             logop_head                  = (xlog_op_header_t *)ptr;
1741             INT_SET(logop_head->oh_tid, ARCH_CONVERT, ticket->t_tid);
1742             logop_head->oh_clientid     = ticket->t_clientid;
1743             INT_ZERO(logop_head->oh_res2, ARCH_CONVERT);
1744
1745             /* header copied directly */
1746             xlog_write_adv_cnt(ptr, len, log_offset, sizeof(xlog_op_header_t));
1747
1748             /* are we copying a commit or unmount record? */
1749             logop_head->oh_flags = flags;
1750
1751             /*
1752              * We've seen logs corrupted with bad transaction client
1753              * ids.  This makes sure that XFS doesn't generate them on.
1754              * Turn this into an EIO and shut down the filesystem.
1755              */
1756             switch (logop_head->oh_clientid)  {
1757             case XFS_TRANSACTION:
1758             case XFS_VOLUME:
1759             case XFS_LOG:
1760                 break;
1761             default:
1762                 xfs_fs_cmn_err(CE_WARN, mp,
1763                     "Bad XFS transaction clientid 0x%x in ticket 0x%p",
1764                     logop_head->oh_clientid, tic);
1765                 return XFS_ERROR(EIO);
1766             }
1767
1768             /* Partial write last time? => (partial_copy != 0)
1769              * need_copy is the amount we'd like to copy if everything could
1770              * fit in the current memcpy.
1771              */
1772             need_copy = reg[index].i_len - partial_copy_len;
1773
1774             copy_off = partial_copy_len;
1775             if (need_copy <= iclog->ic_size - log_offset) { /*complete write */
1776                 INT_SET(logop_head->oh_len, ARCH_CONVERT, copy_len = need_copy);
1777                 if (partial_copy)
1778                     logop_head->oh_flags|= (XLOG_END_TRANS|XLOG_WAS_CONT_TRANS);
1779                 partial_copy_len = partial_copy = 0;
1780             } else {                                        /* partial write */
1781                 copy_len = iclog->ic_size - log_offset;
1782                 INT_SET(logop_head->oh_len, ARCH_CONVERT, copy_len);
1783                 logop_head->oh_flags |= XLOG_CONTINUE_TRANS;
1784                 if (partial_copy)
1785                         logop_head->oh_flags |= XLOG_WAS_CONT_TRANS;
1786                 partial_copy_len += copy_len;
1787                 partial_copy++;
1788                 len += sizeof(xlog_op_header_t); /* from splitting of region */
1789                 /* account for new log op header */
1790                 ticket->t_curr_res -= sizeof(xlog_op_header_t);
1791             }
1792             xlog_verify_dest_ptr(log, ptr);
1793
1794             /* copy region */
1795             ASSERT(copy_len >= 0);
1796             memcpy((xfs_caddr_t)ptr, reg[index].i_addr + copy_off, copy_len);
1797             xlog_write_adv_cnt(ptr, len, log_offset, copy_len);
1798
1799             /* make copy_len total bytes copied, including headers */
1800             copy_len += start_rec_copy + sizeof(xlog_op_header_t);
1801             record_cnt++;
1802             data_cnt += contwr ? copy_len : 0;
1803             firstwr = 0;
1804             if (partial_copy) {                 /* copied partial region */
1805                     /* already marked WANT_SYNC by xlog_state_get_iclog_space */
1806                     xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1807                     record_cnt = data_cnt = 0;
1808                     if ((error = xlog_state_release_iclog(log, iclog)))
1809                             return (error);
1810                     break;                      /* don't increment index */
1811             } else {                            /* copied entire region */
1812                 index++;
1813                 partial_copy_len = partial_copy = 0;
1814
1815                 if (iclog->ic_size - log_offset <= sizeof(xlog_op_header_t)) {
1816                     xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1817                     record_cnt = data_cnt = 0;
1818                     xlog_state_want_sync(log, iclog);
1819                     if (commit_iclog) {
1820                         ASSERT(flags & XLOG_COMMIT_TRANS);
1821                         *commit_iclog = iclog;
1822                     } else if ((error = xlog_state_release_iclog(log, iclog)))
1823                            return (error);
1824                     if (index == nentries)
1825                             return 0;           /* we are done */
1826                     else
1827                             break;
1828                 }
1829             } /* if (partial_copy) */
1830         } /* while (index < nentries) */
1831     } /* for (index = 0; index < nentries; ) */
1832     ASSERT(len == 0);
1833
1834     xlog_state_finish_copy(log, iclog, record_cnt, data_cnt);
1835     if (commit_iclog) {
1836         ASSERT(flags & XLOG_COMMIT_TRANS);
1837         *commit_iclog = iclog;
1838         return 0;
1839     }
1840     return (xlog_state_release_iclog(log, iclog));
1841 }       /* xlog_write */
1842
1843
1844 /*****************************************************************************
1845  *
1846  *              State Machine functions
1847  *
1848  *****************************************************************************
1849  */
1850
1851 /* Clean iclogs starting from the head.  This ordering must be
1852  * maintained, so an iclog doesn't become ACTIVE beyond one that
1853  * is SYNCING.  This is also required to maintain the notion that we use
1854  * a counting semaphore to hold off would be writers to the log when every
1855  * iclog is trying to sync to disk.
1856  *
1857  * State Change: DIRTY -> ACTIVE
1858  */
1859 void
1860 xlog_state_clean_log(xlog_t *log)
1861 {
1862         xlog_in_core_t  *iclog;
1863         int changed = 0;
1864
1865         iclog = log->l_iclog;
1866         do {
1867                 if (iclog->ic_state == XLOG_STATE_DIRTY) {
1868                         iclog->ic_state = XLOG_STATE_ACTIVE;
1869                         iclog->ic_offset       = 0;
1870                         iclog->ic_callback      = 0;   /* don't need to free */
1871                         /*
1872                          * If the number of ops in this iclog indicate it just
1873                          * contains the dummy transaction, we can
1874                          * change state into IDLE (the second time around).
1875                          * Otherwise we should change the state into
1876                          * NEED a dummy.
1877                          * We don't need to cover the dummy.
1878                          */
1879                         if (!changed &&
1880                            (INT_GET(iclog->ic_header.h_num_logops, ARCH_CONVERT) == XLOG_COVER_OPS)) {
1881                                 changed = 1;
1882                         } else {
1883                                 /*
1884                                  * We have two dirty iclogs so start over
1885                                  * This could also be num of ops indicates
1886                                  * this is not the dummy going out.
1887                                  */
1888                                 changed = 2;
1889                         }
1890                         INT_ZERO(iclog->ic_header.h_num_logops, ARCH_CONVERT);
1891                         memset(iclog->ic_header.h_cycle_data, 0,
1892                               sizeof(iclog->ic_header.h_cycle_data));
1893                         INT_ZERO(iclog->ic_header.h_lsn, ARCH_CONVERT);
1894                 } else if (iclog->ic_state == XLOG_STATE_ACTIVE)
1895                         /* do nothing */;
1896                 else
1897                         break;  /* stop cleaning */
1898                 iclog = iclog->ic_next;
1899         } while (iclog != log->l_iclog);
1900
1901         /* log is locked when we are called */
1902         /*
1903          * Change state for the dummy log recording.
1904          * We usually go to NEED. But we go to NEED2 if the changed indicates
1905          * we are done writing the dummy record.
1906          * If we are done with the second dummy recored (DONE2), then
1907          * we go to IDLE.
1908          */
1909         if (changed) {
1910                 switch (log->l_covered_state) {
1911                 case XLOG_STATE_COVER_IDLE:
1912                 case XLOG_STATE_COVER_NEED:
1913                 case XLOG_STATE_COVER_NEED2:
1914                         log->l_covered_state = XLOG_STATE_COVER_NEED;
1915                         break;
1916
1917                 case XLOG_STATE_COVER_DONE:
1918                         if (changed == 1)
1919                                 log->l_covered_state = XLOG_STATE_COVER_NEED2;
1920                         else
1921                                 log->l_covered_state = XLOG_STATE_COVER_NEED;
1922                         break;
1923
1924                 case XLOG_STATE_COVER_DONE2:
1925                         if (changed == 1)
1926                                 log->l_covered_state = XLOG_STATE_COVER_IDLE;
1927                         else
1928                                 log->l_covered_state = XLOG_STATE_COVER_NEED;
1929                         break;
1930
1931                 default:
1932                         ASSERT(0);
1933                 }
1934         }
1935 }       /* xlog_state_clean_log */
1936
1937 STATIC xfs_lsn_t
1938 xlog_get_lowest_lsn(
1939         xlog_t          *log)
1940 {
1941         xlog_in_core_t  *lsn_log;
1942         xfs_lsn_t       lowest_lsn, lsn;
1943
1944         lsn_log = log->l_iclog;
1945         lowest_lsn = 0;
1946         do {
1947             if (!(lsn_log->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY))) {
1948                 lsn = INT_GET(lsn_log->ic_header.h_lsn, ARCH_CONVERT);
1949                 if ((lsn && !lowest_lsn) ||
1950                     (XFS_LSN_CMP_ARCH(lsn, lowest_lsn, ARCH_NOCONVERT) < 0)) {
1951                         lowest_lsn = lsn;
1952                 }
1953             }
1954             lsn_log = lsn_log->ic_next;
1955         } while (lsn_log != log->l_iclog);
1956         return(lowest_lsn);
1957 }
1958
1959
1960 STATIC void
1961 xlog_state_do_callback(
1962         xlog_t          *log,
1963         int             aborted,
1964         xlog_in_core_t  *ciclog)
1965 {
1966         xlog_in_core_t     *iclog;
1967         xlog_in_core_t     *first_iclog;        /* used to know when we've
1968                                                  * processed all iclogs once */
1969         xfs_log_callback_t *cb, *cb_next;
1970         int                flushcnt = 0;
1971         xfs_lsn_t          lowest_lsn;
1972         int                ioerrors;    /* counter: iclogs with errors */
1973         int                loopdidcallbacks; /* flag: inner loop did callbacks*/
1974         int                funcdidcallbacks; /* flag: function did callbacks */
1975         int                repeats;     /* for issuing console warnings if
1976                                          * looping too many times */
1977         SPLDECL(s);
1978
1979         s = LOG_LOCK(log);
1980         first_iclog = iclog = log->l_iclog;
1981         ioerrors = 0;
1982         funcdidcallbacks = 0;
1983         repeats = 0;
1984
1985         do {
1986                 /*
1987                  * Scan all iclogs starting with the one pointed to by the
1988                  * log.  Reset this starting point each time the log is
1989                  * unlocked (during callbacks).
1990                  *
1991                  * Keep looping through iclogs until one full pass is made
1992                  * without running any callbacks.
1993                  */
1994                 first_iclog = log->l_iclog;
1995                 iclog = log->l_iclog;
1996                 loopdidcallbacks = 0;
1997                 repeats++;
1998
1999                 do {
2000
2001                         /* skip all iclogs in the ACTIVE & DIRTY states */
2002                         if (iclog->ic_state &
2003                             (XLOG_STATE_ACTIVE|XLOG_STATE_DIRTY)) {
2004                                 iclog = iclog->ic_next;
2005                                 continue;
2006                         }
2007
2008                         /*
2009                          * Between marking a filesystem SHUTDOWN and stopping
2010                          * the log, we do flush all iclogs to disk (if there
2011                          * wasn't a log I/O error). So, we do want things to
2012                          * go smoothly in case of just a SHUTDOWN  w/o a
2013                          * LOG_IO_ERROR.
2014                          */
2015                         if (!(iclog->ic_state & XLOG_STATE_IOERROR)) {
2016                                 /*
2017                                  * Can only perform callbacks in order.  Since
2018                                  * this iclog is not in the DONE_SYNC/
2019                                  * DO_CALLBACK state, we skip the rest and
2020                                  * just try to clean up.  If we set our iclog
2021                                  * to DO_CALLBACK, we will not process it when
2022                                  * we retry since a previous iclog is in the
2023                                  * CALLBACK and the state cannot change since
2024                                  * we are holding the LOG_LOCK.
2025                                  */
2026                                 if (!(iclog->ic_state &
2027                                         (XLOG_STATE_DONE_SYNC |
2028                                                  XLOG_STATE_DO_CALLBACK))) {
2029                                         if (ciclog && (ciclog->ic_state ==
2030                                                         XLOG_STATE_DONE_SYNC)) {
2031                                                 ciclog->ic_state = XLOG_STATE_DO_CALLBACK;
2032                                         }
2033                                         break;
2034                                 }
2035                                 /*
2036                                  * We now have an iclog that is in either the
2037                                  * DO_CALLBACK or DONE_SYNC states. The other
2038                                  * states (WANT_SYNC, SYNCING, or CALLBACK were
2039                                  * caught by the above if and are going to
2040                                  * clean (i.e. we aren't doing their callbacks)
2041                                  * see the above if.
2042                                  */
2043
2044                                 /*
2045                                  * We will do one more check here to see if we
2046                                  * have chased our tail around.
2047                                  */
2048
2049                                 lowest_lsn = xlog_get_lowest_lsn(log);
2050                                 if (lowest_lsn && (
2051                                         XFS_LSN_CMP_ARCH(
2052                                                 lowest_lsn,
2053                                                 INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT),
2054                                                 ARCH_NOCONVERT
2055                                         )<0)) {
2056                                         iclog = iclog->ic_next;
2057                                         continue; /* Leave this iclog for
2058                                                    * another thread */
2059                                 }
2060
2061                                 iclog->ic_state = XLOG_STATE_CALLBACK;
2062
2063                                 LOG_UNLOCK(log, s);
2064
2065                                 /* l_last_sync_lsn field protected by
2066                                  * GRANT_LOCK. Don't worry about iclog's lsn.
2067                                  * No one else can be here except us.
2068                                  */
2069                                 s = GRANT_LOCK(log);
2070                                 ASSERT(XFS_LSN_CMP_ARCH(
2071                                                 log->l_last_sync_lsn,
2072                                                 INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT),
2073                                                 ARCH_NOCONVERT
2074                                         )<=0);
2075                                 log->l_last_sync_lsn = INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT);
2076                                 GRANT_UNLOCK(log, s);
2077
2078                                 /*
2079                                  * Keep processing entries in the callback list
2080                                  * until we come around and it is empty.  We
2081                                  * need to atomically see that the list is
2082                                  * empty and change the state to DIRTY so that
2083                                  * we don't miss any more callbacks being added.
2084                                  */
2085                                 s = LOG_LOCK(log);
2086                         } else {
2087                                 ioerrors++;
2088                         }
2089                         cb = iclog->ic_callback;
2090
2091                         while (cb != 0) {
2092                                 iclog->ic_callback_tail = &(iclog->ic_callback);
2093                                 iclog->ic_callback = 0;
2094                                 LOG_UNLOCK(log, s);
2095
2096                                 /* perform callbacks in the order given */
2097                                 for (; cb != 0; cb = cb_next) {
2098                                         cb_next = cb->cb_next;
2099                                         cb->cb_func(cb->cb_arg, aborted);
2100                                 }
2101                                 s = LOG_LOCK(log);
2102                                 cb = iclog->ic_callback;
2103                         }
2104
2105                         loopdidcallbacks++;
2106                         funcdidcallbacks++;
2107
2108                         ASSERT(iclog->ic_callback == 0);
2109                         if (!(iclog->ic_state & XLOG_STATE_IOERROR))
2110                                 iclog->ic_state = XLOG_STATE_DIRTY;
2111
2112                         /*
2113                          * Transition from DIRTY to ACTIVE if applicable.
2114                          * NOP if STATE_IOERROR.
2115                          */
2116                         xlog_state_clean_log(log);
2117
2118                         /* wake up threads waiting in xfs_log_force() */
2119                         sv_broadcast(&iclog->ic_forcesema);
2120
2121                         iclog = iclog->ic_next;
2122                 } while (first_iclog != iclog);
2123                 if (repeats && (repeats % 10) == 0) {
2124                         xfs_fs_cmn_err(CE_WARN, log->l_mp,
2125                                 "xlog_state_do_callback: looping %d", repeats);
2126                 }
2127         } while (!ioerrors && loopdidcallbacks);
2128
2129         /*
2130          * make one last gasp attempt to see if iclogs are being left in
2131          * limbo..
2132          */
2133 #ifdef DEBUG
2134         if (funcdidcallbacks) {
2135                 first_iclog = iclog = log->l_iclog;
2136                 do {
2137                         ASSERT(iclog->ic_state != XLOG_STATE_DO_CALLBACK);
2138                         /*
2139                          * Terminate the loop if iclogs are found in states
2140                          * which will cause other threads to clean up iclogs.
2141                          *
2142                          * SYNCING - i/o completion will go through logs
2143                          * DONE_SYNC - interrupt thread should be waiting for
2144                          *              LOG_LOCK
2145                          * IOERROR - give up hope all ye who enter here
2146                          */
2147                         if (iclog->ic_state == XLOG_STATE_WANT_SYNC ||
2148                             iclog->ic_state == XLOG_STATE_SYNCING ||
2149                             iclog->ic_state == XLOG_STATE_DONE_SYNC ||
2150                             iclog->ic_state == XLOG_STATE_IOERROR )
2151                                 break;
2152                         iclog = iclog->ic_next;
2153                 } while (first_iclog != iclog);
2154         }
2155 #endif
2156
2157         if (log->l_iclog->ic_state & (XLOG_STATE_ACTIVE|XLOG_STATE_IOERROR)) {
2158                 flushcnt = log->l_flushcnt;
2159                 log->l_flushcnt = 0;
2160         }
2161         LOG_UNLOCK(log, s);
2162         while (flushcnt--)
2163                 vsema(&log->l_flushsema);
2164 }       /* xlog_state_do_callback */
2165
2166
2167 /*
2168  * Finish transitioning this iclog to the dirty state.
2169  *
2170  * Make sure that we completely execute this routine only when this is
2171  * the last call to the iclog.  There is a good chance that iclog flushes,
2172  * when we reach the end of the physical log, get turned into 2 separate
2173  * calls to bwrite.  Hence, one iclog flush could generate two calls to this
2174  * routine.  By using the reference count bwritecnt, we guarantee that only
2175  * the second completion goes through.
2176  *
2177  * Callbacks could take time, so they are done outside the scope of the
2178  * global state machine log lock.  Assume that the calls to cvsema won't
2179  * take a long time.  At least we know it won't sleep.
2180  */
2181 void
2182 xlog_state_done_syncing(
2183         xlog_in_core_t  *iclog,
2184         int             aborted)
2185 {
2186         xlog_t             *log = iclog->ic_log;
2187         SPLDECL(s);
2188
2189         s = LOG_LOCK(log);
2190
2191         ASSERT(iclog->ic_state == XLOG_STATE_SYNCING ||
2192                iclog->ic_state == XLOG_STATE_IOERROR);
2193         ASSERT(iclog->ic_refcnt == 0);
2194         ASSERT(iclog->ic_bwritecnt == 1 || iclog->ic_bwritecnt == 2);
2195
2196
2197         /*
2198          * If we got an error, either on the first buffer, or in the case of
2199          * split log writes, on the second, we mark ALL iclogs STATE_IOERROR,
2200          * and none should ever be attempted to be written to disk
2201          * again.
2202          */
2203         if (iclog->ic_state != XLOG_STATE_IOERROR) {
2204                 if (--iclog->ic_bwritecnt == 1) {
2205                         LOG_UNLOCK(log, s);
2206                         return;
2207                 }
2208                 iclog->ic_state = XLOG_STATE_DONE_SYNC;
2209         }
2210
2211         /*
2212          * Someone could be sleeping prior to writing out the next
2213          * iclog buffer, we wake them all, one will get to do the
2214          * I/O, the others get to wait for the result.
2215          */
2216         sv_broadcast(&iclog->ic_writesema);
2217         LOG_UNLOCK(log, s);
2218         xlog_state_do_callback(log, aborted, iclog);    /* also cleans log */
2219 }       /* xlog_state_done_syncing */
2220
2221
2222 /*
2223  * If the head of the in-core log ring is not (ACTIVE or DIRTY), then we must
2224  * sleep.  The flush semaphore is set to the number of in-core buffers and
2225  * decremented around disk syncing.  Therefore, if all buffers are syncing,
2226  * this semaphore will cause new writes to sleep until a sync completes.
2227  * Otherwise, this code just does p() followed by v().  This approximates
2228  * a sleep/wakeup except we can't race.
2229  *
2230  * The in-core logs are used in a circular fashion. They are not used
2231  * out-of-order even when an iclog past the head is free.
2232  *
2233  * return:
2234  *      * log_offset where xlog_write() can start writing into the in-core
2235  *              log's data space.
2236  *      * in-core log pointer to which xlog_write() should write.
2237  *      * boolean indicating this is a continued write to an in-core log.
2238  *              If this is the last write, then the in-core log's offset field
2239  *              needs to be incremented, depending on the amount of data which
2240  *              is copied.
2241  */
2242 int
2243 xlog_state_get_iclog_space(xlog_t         *log,
2244                            int            len,
2245                            xlog_in_core_t **iclogp,
2246                            xlog_ticket_t  *ticket,
2247                            int            *continued_write,
2248                            int            *logoffsetp)
2249 {
2250         SPLDECL(s);
2251         int               log_offset;
2252         xlog_rec_header_t *head;
2253         xlog_in_core_t    *iclog;
2254         int               error;
2255
2256 restart:
2257         s = LOG_LOCK(log);
2258         if (XLOG_FORCED_SHUTDOWN(log)) {
2259                 LOG_UNLOCK(log, s);
2260                 return XFS_ERROR(EIO);
2261         }
2262
2263         iclog = log->l_iclog;
2264         if (! (iclog->ic_state == XLOG_STATE_ACTIVE)) {
2265                 log->l_flushcnt++;
2266                 LOG_UNLOCK(log, s);
2267                 xlog_trace_iclog(iclog, XLOG_TRACE_SLEEP_FLUSH);
2268                 XFS_STATS_INC(xs_log_noiclogs);
2269                 /* Ensure that log writes happen */
2270                 psema(&log->l_flushsema, PINOD);
2271                 goto restart;
2272         }
2273         ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
2274         head = &iclog->ic_header;
2275
2276         iclog->ic_refcnt++;                     /* prevents sync */
2277         log_offset = iclog->ic_offset;
2278
2279         /* On the 1st write to an iclog, figure out lsn.  This works
2280          * if iclogs marked XLOG_STATE_WANT_SYNC always write out what they are
2281          * committing to.  If the offset is set, that's how many blocks
2282          * must be written.
2283          */
2284         if (log_offset == 0) {
2285                 ticket->t_curr_res -= log->l_iclog_hsize;
2286                 INT_SET(head->h_cycle, ARCH_CONVERT, log->l_curr_cycle);
2287                 ASSIGN_LSN(head->h_lsn, log, ARCH_CONVERT);
2288                 ASSERT(log->l_curr_block >= 0);
2289
2290                 /* round off error from last write with this iclog */
2291                 ticket->t_curr_res -= iclog->ic_roundoff;
2292                 log->l_roundoff -= iclog->ic_roundoff;
2293                 iclog->ic_roundoff = 0;
2294         }
2295
2296         /* If there is enough room to write everything, then do it.  Otherwise,
2297          * claim the rest of the region and make sure the XLOG_STATE_WANT_SYNC
2298          * bit is on, so this will get flushed out.  Don't update ic_offset
2299          * until you know exactly how many bytes get copied.  Therefore, wait
2300          * until later to update ic_offset.
2301          *
2302          * xlog_write() algorithm assumes that at least 2 xlog_op_header_t's
2303          * can fit into remaining data section.
2304          */
2305         if (iclog->ic_size - iclog->ic_offset < 2*sizeof(xlog_op_header_t)) {
2306                 xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2307
2308                 /* If I'm the only one writing to this iclog, sync it to disk */
2309                 if (iclog->ic_refcnt == 1) {
2310                         LOG_UNLOCK(log, s);
2311                         if ((error = xlog_state_release_iclog(log, iclog)))
2312                                 return (error);
2313                 } else {
2314                         iclog->ic_refcnt--;
2315                         LOG_UNLOCK(log, s);
2316                 }
2317                 goto restart;
2318         }
2319
2320         /* Do we have enough room to write the full amount in the remainder
2321          * of this iclog?  Or must we continue a write on the next iclog and
2322          * mark this iclog as completely taken?  In the case where we switch
2323          * iclogs (to mark it taken), this particular iclog will release/sync
2324          * to disk in xlog_write().
2325          */
2326         if (len <= iclog->ic_size - iclog->ic_offset) {
2327                 *continued_write = 0;
2328                 iclog->ic_offset += len;
2329         } else {
2330                 *continued_write = 1;
2331                 xlog_state_switch_iclogs(log, iclog, iclog->ic_size);
2332         }
2333         *iclogp = iclog;
2334
2335         ASSERT(iclog->ic_offset <= iclog->ic_size);
2336         LOG_UNLOCK(log, s);
2337
2338         *logoffsetp = log_offset;
2339         return 0;
2340 }       /* xlog_state_get_iclog_space */
2341
2342 /*
2343  * Atomically get the log space required for a log ticket.
2344  *
2345  * Once a ticket gets put onto the reserveq, it will only return after
2346  * the needed reservation is satisfied.
2347  */
2348 STATIC int
2349 xlog_grant_log_space(xlog_t        *log,
2350                      xlog_ticket_t *tic)
2351 {
2352         int              free_bytes;
2353         int              need_bytes;
2354         SPLDECL(s);
2355 #ifdef DEBUG
2356         xfs_lsn_t        tail_lsn;
2357 #endif
2358
2359
2360 #ifdef DEBUG
2361         if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2362                 panic("grant Recovery problem");
2363 #endif
2364
2365         /* Is there space or do we need to sleep? */
2366         s = GRANT_LOCK(log);
2367         xlog_trace_loggrant(log, tic, "xlog_grant_log_space: enter");
2368
2369         /* something is already sleeping; insert new transaction at end */
2370         if (log->l_reserve_headq) {
2371                 XLOG_INS_TICKETQ(log->l_reserve_headq, tic);
2372                 xlog_trace_loggrant(log, tic,
2373                                     "xlog_grant_log_space: sleep 1");
2374                 /*
2375                  * Gotta check this before going to sleep, while we're
2376                  * holding the grant lock.
2377                  */
2378                 if (XLOG_FORCED_SHUTDOWN(log))
2379                         goto error_return;
2380
2381                 XFS_STATS_INC(xs_sleep_logspace);
2382                 sv_wait(&tic->t_sema, PINOD|PLTWAIT, &log->l_grant_lock, s);
2383                 /*
2384                  * If we got an error, and the filesystem is shutting down,
2385                  * we'll catch it down below. So just continue...
2386                  */
2387                 xlog_trace_loggrant(log, tic,
2388                                     "xlog_grant_log_space: wake 1");
2389                 s = GRANT_LOCK(log);
2390         }
2391         if (tic->t_flags & XFS_LOG_PERM_RESERV)
2392                 need_bytes = tic->t_unit_res*tic->t_ocnt;
2393         else
2394                 need_bytes = tic->t_unit_res;
2395
2396 redo:
2397         if (XLOG_FORCED_SHUTDOWN(log))
2398                 goto error_return;
2399
2400         free_bytes = xlog_space_left(log, log->l_grant_reserve_cycle,
2401                                      log->l_grant_reserve_bytes);
2402         if (free_bytes < need_bytes) {
2403                 if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2404                         XLOG_INS_TICKETQ(log->l_reserve_headq, tic);
2405                 xlog_trace_loggrant(log, tic,
2406                                     "xlog_grant_log_space: sleep 2");
2407                 XFS_STATS_INC(xs_sleep_logspace);
2408                 sv_wait(&tic->t_sema, PINOD|PLTWAIT, &log->l_grant_lock, s);
2409
2410                 if (XLOG_FORCED_SHUTDOWN(log)) {
2411                         s = GRANT_LOCK(log);
2412                         goto error_return;
2413                 }
2414
2415                 xlog_trace_loggrant(log, tic,
2416                                     "xlog_grant_log_space: wake 2");
2417                 xlog_grant_push_ail(log->l_mp, need_bytes);
2418                 s = GRANT_LOCK(log);
2419                 goto redo;
2420         } else if (tic->t_flags & XLOG_TIC_IN_Q)
2421                 XLOG_DEL_TICKETQ(log->l_reserve_headq, tic);
2422
2423         /* we've got enough space */
2424         XLOG_GRANT_ADD_SPACE(log, need_bytes, 'w');
2425         XLOG_GRANT_ADD_SPACE(log, need_bytes, 'r');
2426 #ifdef DEBUG
2427         tail_lsn = log->l_tail_lsn;
2428         /*
2429          * Check to make sure the grant write head didn't just over lap the
2430          * tail.  If the cycles are the same, we can't be overlapping.
2431          * Otherwise, make sure that the cycles differ by exactly one and
2432          * check the byte count.
2433          */
2434         if (CYCLE_LSN(tail_lsn, ARCH_NOCONVERT) != log->l_grant_write_cycle) {
2435                 ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn, ARCH_NOCONVERT));
2436                 ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn, ARCH_NOCONVERT)));
2437         }
2438 #endif
2439         xlog_trace_loggrant(log, tic, "xlog_grant_log_space: exit");
2440         xlog_verify_grant_head(log, 1);
2441         GRANT_UNLOCK(log, s);
2442         return 0;
2443
2444  error_return:
2445         if (tic->t_flags & XLOG_TIC_IN_Q)
2446                 XLOG_DEL_TICKETQ(log->l_reserve_headq, tic);
2447         xlog_trace_loggrant(log, tic, "xlog_grant_log_space: err_ret");
2448         /*
2449          * If we are failing, make sure the ticket doesn't have any
2450          * current reservations. We don't want to add this back when
2451          * the ticket/transaction gets cancelled.
2452          */
2453         tic->t_curr_res = 0;
2454         tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2455         GRANT_UNLOCK(log, s);
2456         return XFS_ERROR(EIO);
2457 }       /* xlog_grant_log_space */
2458
2459
2460 /*
2461  * Replenish the byte reservation required by moving the grant write head.
2462  *
2463  *
2464  */
2465 STATIC int
2466 xlog_regrant_write_log_space(xlog_t        *log,
2467                              xlog_ticket_t *tic)
2468 {
2469         SPLDECL(s);
2470         int             free_bytes, need_bytes;
2471         xlog_ticket_t   *ntic;
2472 #ifdef DEBUG
2473         xfs_lsn_t       tail_lsn;
2474 #endif
2475
2476         tic->t_curr_res = tic->t_unit_res;
2477
2478         if (tic->t_cnt > 0)
2479                 return (0);
2480
2481 #ifdef DEBUG
2482         if (log->l_flags & XLOG_ACTIVE_RECOVERY)
2483                 panic("regrant Recovery problem");
2484 #endif
2485
2486         s = GRANT_LOCK(log);
2487         xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: enter");
2488
2489         if (XLOG_FORCED_SHUTDOWN(log))
2490                 goto error_return;
2491
2492         /* If there are other waiters on the queue then give them a
2493          * chance at logspace before us. Wake up the first waiters,
2494          * if we do not wake up all the waiters then go to sleep waiting
2495          * for more free space, otherwise try to get some space for
2496          * this transaction.
2497          */
2498
2499         if ((ntic = log->l_write_headq)) {
2500                 free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2501                                              log->l_grant_write_bytes);
2502                 do {
2503                         ASSERT(ntic->t_flags & XLOG_TIC_PERM_RESERV);
2504
2505                         if (free_bytes < ntic->t_unit_res)
2506                                 break;
2507                         free_bytes -= ntic->t_unit_res;
2508                         sv_signal(&ntic->t_sema);
2509                         ntic = ntic->t_next;
2510                 } while (ntic != log->l_write_headq);
2511
2512                 if (ntic != log->l_write_headq) {
2513                         if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2514                                 XLOG_INS_TICKETQ(log->l_write_headq, tic);
2515
2516                         xlog_trace_loggrant(log, tic,
2517                                     "xlog_regrant_write_log_space: sleep 1");
2518                         XFS_STATS_INC(xs_sleep_logspace);
2519                         sv_wait(&tic->t_sema, PINOD|PLTWAIT,
2520                                 &log->l_grant_lock, s);
2521
2522                         /* If we're shutting down, this tic is already
2523                          * off the queue */
2524                         if (XLOG_FORCED_SHUTDOWN(log)) {
2525                                 s = GRANT_LOCK(log);
2526                                 goto error_return;
2527                         }
2528
2529                         xlog_trace_loggrant(log, tic,
2530                                     "xlog_regrant_write_log_space: wake 1");
2531                         xlog_grant_push_ail(log->l_mp, tic->t_unit_res);
2532                         s = GRANT_LOCK(log);
2533                 }
2534         }
2535
2536         need_bytes = tic->t_unit_res;
2537
2538 redo:
2539         if (XLOG_FORCED_SHUTDOWN(log))
2540                 goto error_return;
2541
2542         free_bytes = xlog_space_left(log, log->l_grant_write_cycle,
2543                                      log->l_grant_write_bytes);
2544         if (free_bytes < need_bytes) {
2545                 if ((tic->t_flags & XLOG_TIC_IN_Q) == 0)
2546                         XLOG_INS_TICKETQ(log->l_write_headq, tic);
2547                 XFS_STATS_INC(xs_sleep_logspace);
2548                 sv_wait(&tic->t_sema, PINOD|PLTWAIT, &log->l_grant_lock, s);
2549
2550                 /* If we're shutting down, this tic is already off the queue */
2551                 if (XLOG_FORCED_SHUTDOWN(log)) {
2552                         s = GRANT_LOCK(log);
2553                         goto error_return;
2554                 }
2555
2556                 xlog_trace_loggrant(log, tic,
2557                                     "xlog_regrant_write_log_space: wake 2");
2558                 xlog_grant_push_ail(log->l_mp, need_bytes);
2559                 s = GRANT_LOCK(log);
2560                 goto redo;
2561         } else if (tic->t_flags & XLOG_TIC_IN_Q)
2562                 XLOG_DEL_TICKETQ(log->l_write_headq, tic);
2563
2564         XLOG_GRANT_ADD_SPACE(log, need_bytes, 'w'); /* we've got enough space */
2565 #ifdef DEBUG
2566         tail_lsn = log->l_tail_lsn;
2567         if (CYCLE_LSN(tail_lsn, ARCH_NOCONVERT) != log->l_grant_write_cycle) {
2568                 ASSERT(log->l_grant_write_cycle-1 == CYCLE_LSN(tail_lsn, ARCH_NOCONVERT));
2569                 ASSERT(log->l_grant_write_bytes <= BBTOB(BLOCK_LSN(tail_lsn, ARCH_NOCONVERT)));
2570         }
2571 #endif
2572
2573         xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: exit");
2574         xlog_verify_grant_head(log, 1);
2575         GRANT_UNLOCK(log, s);
2576         return (0);
2577
2578
2579  error_return:
2580         if (tic->t_flags & XLOG_TIC_IN_Q)
2581                 XLOG_DEL_TICKETQ(log->l_reserve_headq, tic);
2582         xlog_trace_loggrant(log, tic, "xlog_regrant_write_log_space: err_ret");
2583         /*
2584          * If we are failing, make sure the ticket doesn't have any
2585          * current reservations. We don't want to add this back when
2586          * the ticket/transaction gets cancelled.
2587          */
2588         tic->t_curr_res = 0;
2589         tic->t_cnt = 0; /* ungrant will give back unit_res * t_cnt. */
2590         GRANT_UNLOCK(log, s);
2591         return XFS_ERROR(EIO);
2592 }       /* xlog_regrant_write_log_space */
2593
2594
2595 /* The first cnt-1 times through here we don't need to
2596  * move the grant write head because the permanent
2597  * reservation has reserved cnt times the unit amount.
2598  * Release part of current permanent unit reservation and
2599  * reset current reservation to be one units worth.  Also
2600  * move grant reservation head forward.
2601  */
2602 STATIC void
2603 xlog_regrant_reserve_log_space(xlog_t        *log,
2604                                xlog_ticket_t *ticket)
2605 {
2606         SPLDECL(s);
2607
2608         xlog_trace_loggrant(log, ticket,
2609                             "xlog_regrant_reserve_log_space: enter");
2610         if (ticket->t_cnt > 0)
2611                 ticket->t_cnt--;
2612
2613         s = GRANT_LOCK(log);
2614         XLOG_GRANT_SUB_SPACE(log, ticket->t_curr_res, 'w');
2615         XLOG_GRANT_SUB_SPACE(log, ticket->t_curr_res, 'r');
2616         ticket->t_curr_res = ticket->t_unit_res;
2617         xlog_trace_loggrant(log, ticket,
2618                             "xlog_regrant_reserve_log_space: sub current res");
2619         xlog_verify_grant_head(log, 1);
2620
2621         /* just return if we still have some of the pre-reserved space */
2622         if (ticket->t_cnt > 0) {
2623                 GRANT_UNLOCK(log, s);
2624                 return;
2625         }
2626
2627         XLOG_GRANT_ADD_SPACE(log, ticket->t_unit_res, 'r');
2628         xlog_trace_loggrant(log, ticket,
2629                             "xlog_regrant_reserve_log_space: exit");
2630         xlog_verify_grant_head(log, 0);
2631         GRANT_UNLOCK(log, s);
2632         ticket->t_curr_res = ticket->t_unit_res;
2633 }       /* xlog_regrant_reserve_log_space */
2634
2635
2636 /*
2637  * Give back the space left from a reservation.
2638  *
2639  * All the information we need to make a correct determination of space left
2640  * is present.  For non-permanent reservations, things are quite easy.  The
2641  * count should have been decremented to zero.  We only need to deal with the
2642  * space remaining in the current reservation part of the ticket.  If the
2643  * ticket contains a permanent reservation, there may be left over space which
2644  * needs to be released.  A count of N means that N-1 refills of the current
2645  * reservation can be done before we need to ask for more space.  The first
2646  * one goes to fill up the first current reservation.  Once we run out of
2647  * space, the count will stay at zero and the only space remaining will be
2648  * in the current reservation field.
2649  */
2650 STATIC void
2651 xlog_ungrant_log_space(xlog_t        *log,
2652                        xlog_ticket_t *ticket)
2653 {
2654         SPLDECL(s);
2655
2656         if (ticket->t_cnt > 0)
2657                 ticket->t_cnt--;
2658
2659         s = GRANT_LOCK(log);
2660         xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: enter");
2661
2662         XLOG_GRANT_SUB_SPACE(log, ticket->t_curr_res, 'w');
2663         XLOG_GRANT_SUB_SPACE(log, ticket->t_curr_res, 'r');
2664
2665         xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: sub current");
2666
2667         /* If this is a permanent reservation ticket, we may be able to free
2668          * up more space based on the remaining count.
2669          */
2670         if (ticket->t_cnt > 0) {
2671                 ASSERT(ticket->t_flags & XLOG_TIC_PERM_RESERV);
2672                 XLOG_GRANT_SUB_SPACE(log, ticket->t_unit_res*ticket->t_cnt,'w');
2673                 XLOG_GRANT_SUB_SPACE(log, ticket->t_unit_res*ticket->t_cnt,'r');
2674         }
2675
2676         xlog_trace_loggrant(log, ticket, "xlog_ungrant_log_space: exit");
2677         xlog_verify_grant_head(log, 1);
2678         GRANT_UNLOCK(log, s);
2679         xfs_log_move_tail(log->l_mp, 1);
2680 }       /* xlog_ungrant_log_space */
2681
2682
2683 /*
2684  * Atomically put back used ticket.
2685  */
2686 void
2687 xlog_state_put_ticket(xlog_t        *log,
2688                       xlog_ticket_t *tic)
2689 {
2690         unsigned long s;
2691
2692         s = LOG_LOCK(log);
2693         xlog_ticket_put(log, tic);
2694         LOG_UNLOCK(log, s);
2695 }       /* xlog_state_put_ticket */
2696
2697 /*
2698  * Flush iclog to disk if this is the last reference to the given iclog and
2699  * the WANT_SYNC bit is set.
2700  *
2701  * When this function is entered, the iclog is not necessarily in the
2702  * WANT_SYNC state.  It may be sitting around waiting to get filled.
2703  *
2704  *
2705  */
2706 int
2707 xlog_state_release_iclog(xlog_t         *log,
2708                          xlog_in_core_t *iclog)
2709 {
2710         SPLDECL(s);
2711         int             sync = 0;       /* do we sync? */
2712
2713         xlog_assign_tail_lsn(log->l_mp);
2714
2715         s = LOG_LOCK(log);
2716
2717         if (iclog->ic_state & XLOG_STATE_IOERROR) {
2718                 LOG_UNLOCK(log, s);
2719                 return XFS_ERROR(EIO);
2720         }
2721
2722         ASSERT(iclog->ic_refcnt > 0);
2723         ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE ||
2724                iclog->ic_state == XLOG_STATE_WANT_SYNC);
2725
2726         if (--iclog->ic_refcnt == 0 &&
2727             iclog->ic_state == XLOG_STATE_WANT_SYNC) {
2728                 sync++;
2729                 iclog->ic_state = XLOG_STATE_SYNCING;
2730                 INT_SET(iclog->ic_header.h_tail_lsn, ARCH_CONVERT, log->l_tail_lsn);
2731                 xlog_verify_tail_lsn(log, iclog, log->l_tail_lsn);
2732                 /* cycle incremented when incrementing curr_block */
2733         }
2734
2735         LOG_UNLOCK(log, s);
2736
2737         /*
2738          * We let the log lock go, so it's possible that we hit a log I/O
2739          * error or someother SHUTDOWN condition that marks the iclog
2740          * as XLOG_STATE_IOERROR before the bwrite. However, we know that
2741          * this iclog has consistent data, so we ignore IOERROR
2742          * flags after this point.
2743          */
2744         if (sync) {
2745                 return xlog_sync(log, iclog);
2746         }
2747         return (0);
2748
2749 }       /* xlog_state_release_iclog */
2750
2751
2752 /*
2753  * This routine will mark the current iclog in the ring as WANT_SYNC
2754  * and move the current iclog pointer to the next iclog in the ring.
2755  * When this routine is called from xlog_state_get_iclog_space(), the
2756  * exact size of the iclog has not yet been determined.  All we know is
2757  * that every data block.  We have run out of space in this log record.
2758  */
2759 STATIC void
2760 xlog_state_switch_iclogs(xlog_t         *log,
2761                          xlog_in_core_t *iclog,
2762                          int            eventual_size)
2763 {
2764         ASSERT(iclog->ic_state == XLOG_STATE_ACTIVE);
2765         if (!eventual_size)
2766                 eventual_size = iclog->ic_offset;
2767         iclog->ic_state = XLOG_STATE_WANT_SYNC;
2768         INT_SET(iclog->ic_header.h_prev_block, ARCH_CONVERT, log->l_prev_block);
2769         log->l_prev_block = log->l_curr_block;
2770         log->l_prev_cycle = log->l_curr_cycle;
2771
2772         /* roll log?: ic_offset changed later */
2773         log->l_curr_block += BTOBB(eventual_size)+BTOBB(log->l_iclog_hsize);
2774
2775         /* Round up to next log-sunit */
2776         if (XFS_SB_VERSION_HASLOGV2(&log->l_mp->m_sb) &&
2777             log->l_mp->m_sb.sb_logsunit > 1) {
2778                 __uint32_t sunit_bb = BTOBB(log->l_mp->m_sb.sb_logsunit);
2779                 log->l_curr_block = roundup(log->l_curr_block, sunit_bb);
2780         }
2781
2782         if (log->l_curr_block >= log->l_logBBsize) {
2783                 log->l_curr_cycle++;
2784                 if (log->l_curr_cycle == XLOG_HEADER_MAGIC_NUM)
2785                         log->l_curr_cycle++;
2786                 log->l_curr_block -= log->l_logBBsize;
2787                 ASSERT(log->l_curr_block >= 0);
2788         }
2789         ASSERT(iclog == log->l_iclog);
2790         log->l_iclog = iclog->ic_next;
2791 }       /* xlog_state_switch_iclogs */
2792
2793
2794 /*
2795  * Write out all data in the in-core log as of this exact moment in time.
2796  *
2797  * Data may be written to the in-core log during this call.  However,
2798  * we don't guarantee this data will be written out.  A change from past
2799  * implementation means this routine will *not* write out zero length LRs.
2800  *
2801  * Basically, we try and perform an intelligent scan of the in-core logs.
2802  * If we determine there is no flushable data, we just return.  There is no
2803  * flushable data if:
2804  *
2805  *      1. the current iclog is active and has no data; the previous iclog
2806  *              is in the active or dirty state.
2807  *      2. the current iclog is drity, and the previous iclog is in the
2808  *              active or dirty state.
2809  *
2810  * We may sleep (call psema) if:
2811  *
2812  *      1. the current iclog is not in the active nor dirty state.
2813  *      2. the current iclog dirty, and the previous iclog is not in the
2814  *              active nor dirty state.
2815  *      3. the current iclog is active, and there is another thread writing
2816  *              to this particular iclog.
2817  *      4. a) the current iclog is active and has no other writers
2818  *         b) when we return from flushing out this iclog, it is still
2819  *              not in the active nor dirty state.
2820  */
2821 STATIC int
2822 xlog_state_sync_all(xlog_t *log, uint flags)
2823 {
2824         xlog_in_core_t  *iclog;
2825         xfs_lsn_t       lsn;
2826         SPLDECL(s);
2827
2828         s = LOG_LOCK(log);
2829
2830         iclog = log->l_iclog;
2831         if (iclog->ic_state & XLOG_STATE_IOERROR) {
2832                 LOG_UNLOCK(log, s);
2833                 return XFS_ERROR(EIO);
2834         }
2835
2836         /* If the head iclog is not active nor dirty, we just attach
2837          * ourselves to the head and go to sleep.
2838          */
2839         if (iclog->ic_state == XLOG_STATE_ACTIVE ||
2840             iclog->ic_state == XLOG_STATE_DIRTY) {
2841                 /*
2842                  * If the head is dirty or (active and empty), then
2843                  * we need to look at the previous iclog.  If the previous
2844                  * iclog is active or dirty we are done.  There is nothing
2845                  * to sync out.  Otherwise, we attach ourselves to the
2846                  * previous iclog and go to sleep.
2847                  */
2848                 if (iclog->ic_state == XLOG_STATE_DIRTY ||
2849                     (iclog->ic_refcnt == 0 && iclog->ic_offset == 0)) {
2850                         iclog = iclog->ic_prev;
2851                         if (iclog->ic_state == XLOG_STATE_ACTIVE ||
2852                             iclog->ic_state == XLOG_STATE_DIRTY)
2853                                 goto no_sleep;
2854                         else
2855                                 goto maybe_sleep;
2856                 } else {
2857                         if (iclog->ic_refcnt == 0) {
2858                                 /* We are the only one with access to this
2859                                  * iclog.  Flush it out now.  There should
2860                                  * be a roundoff of zero to show that someone
2861                                  * has already taken care of the roundoff from
2862                                  * the previous sync.
2863                                  */
2864                                 ASSERT(iclog->ic_roundoff == 0);
2865                                 iclog->ic_refcnt++;
2866                                 lsn = INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT);
2867                                 xlog_state_switch_iclogs(log, iclog, 0);
2868                                 LOG_UNLOCK(log, s);
2869
2870                                 if (xlog_state_release_iclog(log, iclog))
2871                                         return XFS_ERROR(EIO);
2872                                 s = LOG_LOCK(log);
2873                                 if (INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT) == lsn &&
2874                                     iclog->ic_state != XLOG_STATE_DIRTY)
2875                                         goto maybe_sleep;
2876                                 else
2877                                         goto no_sleep;
2878                         } else {
2879                                 /* Someone else is writing to this iclog.
2880                                  * Use its call to flush out the data.  However,
2881                                  * the other thread may not force out this LR,
2882                                  * so we mark it WANT_SYNC.
2883                                  */
2884                                 xlog_state_switch_iclogs(log, iclog, 0);
2885                                 goto maybe_sleep;
2886                         }
2887                 }
2888         }
2889
2890         /* By the time we come around again, the iclog could've been filled
2891          * which would give it another lsn.  If we have a new lsn, just
2892          * return because the relevant data has been flushed.
2893          */
2894 maybe_sleep:
2895         if (flags & XFS_LOG_SYNC) {
2896                 /*
2897                  * We must check if we're shutting down here, before
2898                  * we wait, while we're holding the LOG_LOCK.
2899                  * Then we check again after waking up, in case our
2900                  * sleep was disturbed by a bad news.
2901                  */
2902                 if (iclog->ic_state & XLOG_STATE_IOERROR) {
2903                         LOG_UNLOCK(log, s);
2904                         return XFS_ERROR(EIO);
2905                 }
2906                 XFS_STATS_INC(xs_log_force_sleep);
2907                 sv_wait(&iclog->ic_forcesema, PINOD, &log->l_icloglock, s);
2908                 /*
2909                  * No need to grab the log lock here since we're
2910                  * only deciding whether or not to return EIO
2911                  * and the memory read should be atomic.
2912                  */
2913                 if (iclog->ic_state & XLOG_STATE_IOERROR)
2914                         return XFS_ERROR(EIO);
2915
2916         } else {
2917
2918 no_sleep:
2919                 LOG_UNLOCK(log, s);
2920         }
2921         return 0;
2922 }       /* xlog_state_sync_all */
2923
2924
2925 /*
2926  * Used by code which implements synchronous log forces.
2927  *
2928  * Find in-core log with lsn.
2929  *      If it is in the DIRTY state, just return.
2930  *      If it is in the ACTIVE state, move the in-core log into the WANT_SYNC
2931  *              state and go to sleep or return.
2932  *      If it is in any other state, go to sleep or return.
2933  *
2934  * If filesystem activity goes to zero, the iclog will get flushed only by
2935  * bdflush().
2936  */
2937 int
2938 xlog_state_sync(xlog_t    *log,
2939                 xfs_lsn_t lsn,
2940                 uint      flags)
2941 {
2942     xlog_in_core_t      *iclog;
2943     int                 already_slept = 0;
2944     SPLDECL(s);
2945
2946
2947 try_again:
2948     s = LOG_LOCK(log);
2949     iclog = log->l_iclog;
2950
2951     if (iclog->ic_state & XLOG_STATE_IOERROR) {
2952             LOG_UNLOCK(log, s);
2953             return XFS_ERROR(EIO);
2954     }
2955
2956     do {
2957         if (INT_GET(iclog->ic_header.h_lsn, ARCH_CONVERT) != lsn) {
2958             iclog = iclog->ic_next;
2959             continue;
2960         }
2961
2962         if (iclog->ic_state == XLOG_STATE_DIRTY) {
2963                 LOG_UNLOCK(log, s);
2964                 return 0;
2965         }
2966
2967         if (iclog->ic_state == XLOG_STATE_ACTIVE) {
2968                 /*
2969                  * We sleep here if we haven't already slept (e.g.
2970                  * this is the first time we've looked at the correct
2971                  * iclog buf) and the buffer before us is going to
2972                  * be sync'ed. The reason for this is that if we
2973                  * are doing sync transactions here, by waiting for
2974                  * the previous I/O to complete, we can allow a few
2975                  * more transactions into this iclog before we close
2976                  * it down.
2977                  *
2978                  * Otherwise, we mark the buffer WANT_SYNC, and bump
2979                  * up the refcnt so we can release the log (which drops
2980                  * the ref count).  The state switch keeps new transaction
2981                  * commits from using this buffer.  When the current commits
2982                  * finish writing into the buffer, the refcount will drop to
2983                  * zero and the buffer will go out then.
2984                  */
2985                 if (!already_slept &&
2986                     (iclog->ic_prev->ic_state & (XLOG_STATE_WANT_SYNC |
2987                                                  XLOG_STATE_SYNCING))) {
2988                         ASSERT(!(iclog->ic_state & XLOG_STATE_IOERROR));
2989                         XFS_STATS_INC(xs_log_force_sleep);
2990                         sv_wait(&iclog->ic_prev->ic_writesema, PSWP,
2991                                 &log->l_icloglock, s);
2992                         already_slept = 1;
2993                         goto try_again;
2994                 } else {
2995                         iclog->ic_refcnt++;
2996                         xlog_state_switch_iclogs(log, iclog, 0);
2997                         LOG_UNLOCK(log, s);
2998                         if (xlog_state_release_iclog(log, iclog))
2999                                 return XFS_ERROR(EIO);
3000                         s = LOG_LOCK(log);
3001                 }
3002         }
3003
3004         if ((flags & XFS_LOG_SYNC) && /* sleep */
3005             !(iclog->ic_state & (XLOG_STATE_ACTIVE | XLOG_STATE_DIRTY))) {
3006
3007                 /*
3008                  * Don't wait on the forcesema if we know that we've
3009                  * gotten a log write error.
3010                  */
3011                 if (iclog->ic_state & XLOG_STATE_IOERROR) {
3012                         LOG_UNLOCK(log, s);
3013                         return XFS_ERROR(EIO);
3014                 }
3015                 XFS_STATS_INC(xs_log_force_sleep);
3016                 sv_wait(&iclog->ic_forcesema, PSWP, &log->l_icloglock, s);
3017                 /*
3018                  * No need to grab the log lock here since we're
3019                  * only deciding whether or not to return EIO
3020                  * and the memory read should be atomic.
3021                  */
3022                 if (iclog->ic_state & XLOG_STATE_IOERROR)
3023                         return XFS_ERROR(EIO);
3024         } else {                /* just return */
3025                 LOG_UNLOCK(log, s);
3026         }
3027         return 0;
3028
3029     } while (iclog != log->l_iclog);
3030
3031     LOG_UNLOCK(log, s);
3032     return (0);
3033 }       /* xlog_state_sync */
3034
3035
3036 /*
3037  * Called when we want to mark the current iclog as being ready to sync to
3038  * disk.
3039  */
3040 void
3041 xlog_state_want_sync(xlog_t *log, xlog_in_core_t *iclog)
3042 {
3043         SPLDECL(s);
3044
3045         s = LOG_LOCK(log);
3046
3047         if (iclog->ic_state == XLOG_STATE_ACTIVE) {
3048                 xlog_state_switch_iclogs(log, iclog, 0);
3049         } else {
3050                 ASSERT(iclog->ic_state &
3051                         (XLOG_STATE_WANT_SYNC|XLOG_STATE_IOERROR));
3052         }
3053
3054         LOG_UNLOCK(log, s);
3055 }       /* xlog_state_want_sync */
3056
3057
3058
3059 /*****************************************************************************
3060  *
3061  *              TICKET functions
3062  *
3063  *****************************************************************************
3064  */
3065
3066 /*
3067  *      Algorithm doesn't take into account page size. ;-(
3068  */
3069 STATIC void
3070 xlog_state_ticket_alloc(xlog_t *log)
3071 {
3072         xlog_ticket_t   *t_list;
3073         xlog_ticket_t   *next;
3074         xfs_caddr_t     buf;
3075         uint            i = (NBPP / sizeof(xlog_ticket_t)) - 2;
3076         SPLDECL(s);
3077
3078         /*
3079          * The kmem_zalloc may sleep, so we shouldn't be holding the
3080          * global lock.  XXXmiken: may want to use zone allocator.
3081          */
3082         buf = (xfs_caddr_t) kmem_zalloc(NBPP, KM_SLEEP);
3083
3084         s = LOG_LOCK(log);
3085
3086         /* Attach 1st ticket to Q, so we can keep track of allocated memory */
3087         t_list = (xlog_ticket_t *)buf;
3088         t_list->t_next = log->l_unmount_free;
3089         log->l_unmount_free = t_list++;
3090         log->l_ticket_cnt++;
3091         log->l_ticket_tcnt++;
3092
3093         /* Next ticket becomes first ticket attached to ticket free list */
3094         if (log->l_freelist != NULL) {
3095                 ASSERT(log->l_tail != NULL);
3096                 log->l_tail->t_next = t_list;
3097         } else {
3098                 log->l_freelist = t_list;
3099         }
3100         log->l_ticket_cnt++;
3101         log->l_ticket_tcnt++;
3102
3103         /* Cycle through rest of alloc'ed memory, building up free Q */
3104         for ( ; i > 0; i--) {
3105                 next = t_list + 1;
3106                 t_list->t_next = next;
3107                 t_list = next;
3108                 log->l_ticket_cnt++;
3109                 log->l_ticket_tcnt++;
3110         }
3111         t_list->t_next = 0;
3112         log->l_tail = t_list;
3113         LOG_UNLOCK(log, s);
3114 }       /* xlog_state_ticket_alloc */
3115
3116
3117 /*
3118  * Put ticket into free list
3119  *
3120  * Assumption: log lock is held around this call.
3121  */
3122 STATIC void
3123 xlog_ticket_put(xlog_t          *log,
3124                 xlog_ticket_t   *ticket)
3125 {
3126         sv_destroy(&ticket->t_sema);
3127
3128         /*
3129          * Don't think caching will make that much difference.  It's
3130          * more important to make debug easier.
3131          */
3132 #if 0
3133         /* real code will want to use LIFO for caching */
3134         ticket->t_next = log->l_freelist;
3135         log->l_freelist = ticket;
3136         /* no need to clear fields */
3137 #else
3138         /* When we debug, it is easier if tickets are cycled */
3139         ticket->t_next     = 0;
3140         if (log->l_tail != 0) {
3141                 log->l_tail->t_next = ticket;
3142         } else {
3143                 ASSERT(log->l_freelist == 0);
3144                 log->l_freelist = ticket;
3145         }
3146         log->l_tail         = ticket;
3147 #endif /* DEBUG */
3148         log->l_ticket_cnt++;
3149 }       /* xlog_ticket_put */
3150
3151
3152 /*
3153  * Grab ticket off freelist or allocation some more
3154  */
3155 xlog_ticket_t *
3156 xlog_ticket_get(xlog_t          *log,
3157                 int             unit_bytes,
3158                 int             cnt,
3159                 char            client,
3160                 uint            xflags)
3161 {
3162         xlog_ticket_t   *tic;
3163         uint            num_headers;
3164         SPLDECL(s);
3165
3166  alloc:
3167         if (log->l_freelist == NULL)
3168                 xlog_state_ticket_alloc(log);           /* potentially sleep */
3169
3170         s = LOG_LOCK(log);
3171         if (log->l_freelist == NULL) {
3172                 LOG_UNLOCK(log, s);
3173                 goto alloc;
3174         }
3175         tic             = log->l_freelist;
3176         log->l_freelist = tic->t_next;
3177         if (log->l_freelist == NULL)
3178                 log->l_tail = NULL;
3179         log->l_ticket_cnt--;
3180         LOG_UNLOCK(log, s);
3181
3182         /*
3183          * Permanent reservations have up to 'cnt'-1 active log operations
3184          * in the log.  A unit in this case is the amount of space for one
3185          * of these log operations.  Normal reservations have a cnt of 1
3186          * and their unit amount is the total amount of space required.
3187          *
3188          * The following lines of code account for non-transaction data
3189          * which occupy space in the on-disk log. 
3190          */
3191
3192         /* for start-rec */
3193         unit_bytes += sizeof(xlog_op_header_t); 
3194
3195         /* for padding */
3196         if (XFS_SB_VERSION_HASLOGV2(&log->l_mp->m_sb) &&
3197                 log->l_mp->m_sb.sb_logsunit > 1) {
3198                 /* log su roundoff */
3199                 unit_bytes += log->l_mp->m_sb.sb_logsunit;  
3200         } else {
3201                 /* BB roundoff */
3202                 unit_bytes += BBSIZE;
3203         }
3204
3205         /* for commit-rec */
3206         unit_bytes += sizeof(xlog_op_header_t);
3207  
3208         /* for LR headers */
3209         num_headers = ((unit_bytes + log->l_iclog_size-1) >> log->l_iclog_size_log);
3210         unit_bytes += log->l_iclog_hsize * num_headers;
3211
3212         tic->t_unit_res         = unit_bytes;
3213         tic->t_curr_res         = unit_bytes;
3214         tic->t_cnt              = cnt;
3215         tic->t_ocnt             = cnt;
3216         tic->t_tid              = (xlog_tid_t)((__psint_t)tic & 0xffffffff);
3217         tic->t_clientid         = client;
3218         tic->t_flags            = XLOG_TIC_INITED;
3219         if (xflags & XFS_LOG_PERM_RESERV)
3220                 tic->t_flags |= XLOG_TIC_PERM_RESERV;
3221         sv_init(&(tic->t_sema), SV_DEFAULT, "logtick");
3222
3223         return tic;
3224 }       /* xlog_ticket_get */
3225
3226
3227 /******************************************************************************
3228  *
3229  *              Log debug routines
3230  *
3231  ******************************************************************************
3232  */
3233 #if defined(DEBUG) && !defined(XLOG_NOLOG)
3234 /*
3235  * Make sure that the destination ptr is within the valid data region of
3236  * one of the iclogs.  This uses backup pointers stored in a different
3237  * part of the log in case we trash the log structure.
3238  */
3239 void
3240 xlog_verify_dest_ptr(xlog_t     *log,
3241                      __psint_t  ptr)
3242 {
3243         int i;
3244         int good_ptr = 0;
3245
3246         for (i=0; i < log->l_iclog_bufs; i++) {
3247                 if (ptr >= (__psint_t)log->l_iclog_bak[i] &&
3248                     ptr <= (__psint_t)log->l_iclog_bak[i]+log->l_iclog_size)
3249                         good_ptr++;
3250         }
3251         if (! good_ptr)
3252                 xlog_panic("xlog_verify_dest_ptr: invalid ptr");
3253 }       /* xlog_verify_dest_ptr */
3254
3255
3256 #ifdef XFSDEBUG
3257 /* check split LR write */
3258 STATIC void
3259 xlog_verify_disk_cycle_no(xlog_t         *log,
3260                           xlog_in_core_t *iclog)
3261 {
3262     xfs_buf_t   *bp;
3263     uint        cycle_no;
3264     xfs_caddr_t ptr;
3265     xfs_daddr_t i;
3266
3267     if (BLOCK_LSN(iclog->ic_header.h_lsn, ARCH_CONVERT) < 10) {
3268         cycle_no = CYCLE_LSN(iclog->ic_header.h_lsn, ARCH_CONVERT);
3269         bp = xlog_get_bp(log, 1);
3270         ASSERT(bp);
3271         for (i = 0; i < BLOCK_LSN(iclog->ic_header.h_lsn, ARCH_CONVERT); i++) {
3272             xlog_bread(log, i, 1, bp);
3273             ptr = xlog_align(log, i, 1, bp);
3274             if (GET_CYCLE(ptr, ARCH_CONVERT) != cycle_no)
3275                 xlog_warn("XFS: xlog_verify_disk_cycle_no: bad cycle no");
3276         }
3277         xlog_put_bp(bp);
3278     }
3279 }       /* xlog_verify_disk_cycle_no */
3280 #endif
3281
3282 STATIC void
3283 xlog_verify_grant_head(xlog_t *log, int equals)
3284 {
3285     if (log->l_grant_reserve_cycle == log->l_grant_write_cycle) {
3286         if (equals)
3287             ASSERT(log->l_grant_reserve_bytes >= log->l_grant_write_bytes);
3288         else
3289             ASSERT(log->l_grant_reserve_bytes > log->l_grant_write_bytes);
3290     } else {
3291         ASSERT(log->l_grant_reserve_cycle-1 == log->l_grant_write_cycle);
3292         ASSERT(log->l_grant_write_bytes >= log->l_grant_reserve_bytes);
3293     }
3294 }       /* xlog_verify_grant_head */
3295
3296 /* check if it will fit */
3297 STATIC void
3298 xlog_verify_tail_lsn(xlog_t         *log,
3299                      xlog_in_core_t *iclog,
3300                      xfs_lsn_t      tail_lsn)
3301 {
3302     int blocks;
3303
3304     if (CYCLE_LSN(tail_lsn, ARCH_NOCONVERT) == log->l_prev_cycle) {
3305         blocks =
3306             log->l_logBBsize - (log->l_prev_block - BLOCK_LSN(tail_lsn, ARCH_NOCONVERT));
3307         if (blocks < BTOBB(iclog->ic_offset)+BTOBB(log->l_iclog_hsize))
3308             xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3309     } else {
3310         ASSERT(CYCLE_LSN(tail_lsn, ARCH_NOCONVERT)+1 == log->l_prev_cycle);
3311
3312         if (BLOCK_LSN(tail_lsn, ARCH_NOCONVERT) == log->l_prev_block)
3313             xlog_panic("xlog_verify_tail_lsn: tail wrapped");
3314
3315         blocks = BLOCK_LSN(tail_lsn, ARCH_NOCONVERT) - log->l_prev_block;
3316         if (blocks < BTOBB(iclog->ic_offset) + 1)
3317             xlog_panic("xlog_verify_tail_lsn: ran out of log space");
3318     }
3319 }       /* xlog_verify_tail_lsn */
3320
3321 /*
3322  * Perform a number of checks on the iclog before writing to disk.
3323  *
3324  * 1. Make sure the iclogs are still circular
3325  * 2. Make sure we have a good magic number
3326  * 3. Make sure we don't have magic numbers in the data
3327  * 4. Check fields of each log operation header for:
3328  *      A. Valid client identifier
3329  *      B. tid ptr value falls in valid ptr space (user space code)
3330  *      C. Length in log record header is correct according to the
3331  *              individual operation headers within record.
3332  * 5. When a bwrite will occur within 5 blocks of the front of the physical
3333  *      log, check the preceding blocks of the physical log to make sure all
3334  *      the cycle numbers agree with the current cycle number.
3335  */
3336 STATIC void
3337 xlog_verify_iclog(xlog_t         *log,
3338                   xlog_in_core_t *iclog,
3339                   int            count,
3340                   boolean_t      syncing)
3341 {
3342         xlog_op_header_t        *ophead;
3343         xlog_in_core_t          *icptr;
3344         xlog_in_core_2_t        *xhdr;
3345         xfs_caddr_t             ptr;
3346         xfs_caddr_t             base_ptr;
3347         __psint_t               field_offset;
3348         __uint8_t               clientid;
3349         int                     len, i, j, k, op_len;
3350         int                     idx;
3351         SPLDECL(s);
3352
3353         /* check validity of iclog pointers */
3354         s = LOG_LOCK(log);
3355         icptr = log->l_iclog;
3356         for (i=0; i < log->l_iclog_bufs; i++) {
3357                 if (icptr == 0)
3358                         xlog_panic("xlog_verify_iclog: invalid ptr");
3359                 icptr = icptr->ic_next;
3360         }
3361         if (icptr != log->l_iclog)
3362                 xlog_panic("xlog_verify_iclog: corrupt iclog ring");
3363         LOG_UNLOCK(log, s);
3364
3365         /* check log magic numbers */
3366         ptr = (xfs_caddr_t) &(iclog->ic_header);
3367         if (INT_GET(*(uint *)ptr, ARCH_CONVERT) != XLOG_HEADER_MAGIC_NUM)
3368                 xlog_panic("xlog_verify_iclog: invalid magic num");
3369
3370         for (ptr += BBSIZE; ptr < ((xfs_caddr_t)&(iclog->ic_header))+count;
3371              ptr += BBSIZE) {
3372                 if (INT_GET(*(uint *)ptr, ARCH_CONVERT) == XLOG_HEADER_MAGIC_NUM)
3373                         xlog_panic("xlog_verify_iclog: unexpected magic num");
3374         }
3375
3376         /* check fields */
3377         len = INT_GET(iclog->ic_header.h_num_logops, ARCH_CONVERT);
3378         ptr = iclog->ic_datap;
3379         base_ptr = ptr;
3380         ophead = (xlog_op_header_t *)ptr;
3381         xhdr = (xlog_in_core_2_t *)&iclog->ic_header;
3382         for (i = 0; i < len; i++) {
3383                 ophead = (xlog_op_header_t *)ptr;
3384
3385                 /* clientid is only 1 byte */
3386                 field_offset = (__psint_t)
3387                                ((xfs_caddr_t)&(ophead->oh_clientid) - base_ptr);
3388                 if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3389                         clientid = ophead->oh_clientid;
3390                 } else {
3391                         idx = BTOBBT((xfs_caddr_t)&(ophead->oh_clientid) - iclog->ic_datap);
3392                         if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3393                                 j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3394                                 k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3395                                 clientid = GET_CLIENT_ID(xhdr[j].hic_xheader.xh_cycle_data[k], ARCH_CONVERT);
3396                         } else {
3397                                 clientid = GET_CLIENT_ID(iclog->ic_header.h_cycle_data[idx], ARCH_CONVERT);
3398                         }
3399                 }
3400                 if (clientid != XFS_TRANSACTION && clientid != XFS_LOG)
3401                         cmn_err(CE_WARN, "xlog_verify_iclog: invalid clientid %d op 0x%p offset 0x%x", clientid, ophead, field_offset);
3402
3403                 /* check length */
3404                 field_offset = (__psint_t)
3405                                ((xfs_caddr_t)&(ophead->oh_len) - base_ptr);
3406                 if (syncing == B_FALSE || (field_offset & 0x1ff)) {
3407                         op_len = INT_GET(ophead->oh_len, ARCH_CONVERT);
3408                 } else {
3409                         idx = BTOBBT((__psint_t)&ophead->oh_len -
3410                                     (__psint_t)iclog->ic_datap);
3411                         if (idx >= (XLOG_HEADER_CYCLE_SIZE / BBSIZE)) {
3412                                 j = idx / (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3413                                 k = idx % (XLOG_HEADER_CYCLE_SIZE / BBSIZE);
3414                                 op_len = INT_GET(xhdr[j].hic_xheader.xh_cycle_data[k], ARCH_CONVERT);
3415                         } else {
3416                                 op_len = INT_GET(iclog->ic_header.h_cycle_data[idx], ARCH_CONVERT);
3417                         }
3418                 }
3419                 ptr += sizeof(xlog_op_header_t) + op_len;
3420         }
3421 }       /* xlog_verify_iclog */
3422 #endif /* DEBUG && !XLOG_NOLOG */
3423
3424 /*
3425  * Mark all iclogs IOERROR. LOG_LOCK is held by the caller.
3426  */
3427 STATIC int
3428 xlog_state_ioerror(
3429         xlog_t  *log)
3430 {
3431         xlog_in_core_t  *iclog, *ic;
3432
3433         iclog = log->l_iclog;
3434         if (! (iclog->ic_state & XLOG_STATE_IOERROR)) {
3435                 /*
3436                  * Mark all the incore logs IOERROR.
3437                  * From now on, no log flushes will result.
3438                  */
3439                 ic = iclog;
3440                 do {
3441                         ic->ic_state = XLOG_STATE_IOERROR;
3442                         ic = ic->ic_next;
3443                 } while (ic != iclog);
3444                 return (0);
3445         }
3446         /*
3447          * Return non-zero, if state transition has already happened.
3448          */
3449         return (1);
3450 }
3451
3452 /*
3453  * This is called from xfs_force_shutdown, when we're forcibly
3454  * shutting down the filesystem, typically because of an IO error.
3455  * Our main objectives here are to make sure that:
3456  *      a. the filesystem gets marked 'SHUTDOWN' for all interested
3457  *         parties to find out, 'atomically'.
3458  *      b. those who're sleeping on log reservations, pinned objects and
3459  *          other resources get woken up, and be told the bad news.
3460  *      c. nothing new gets queued up after (a) and (b) are done.
3461  *      d. if !logerror, flush the iclogs to disk, then seal them off
3462  *         for business.
3463  */
3464 int
3465 xfs_log_force_umount(
3466         struct xfs_mount        *mp,
3467         int                     logerror)
3468 {
3469         xlog_ticket_t   *tic;
3470         xlog_t          *log;
3471         int             retval;
3472         SPLDECL(s);
3473         SPLDECL(s2);
3474
3475         log = mp->m_log;
3476
3477         /*
3478          * If this happens during log recovery, don't worry about
3479          * locking; the log isn't open for business yet.
3480          */
3481         if (!log ||
3482             log->l_flags & XLOG_ACTIVE_RECOVERY) {
3483                 mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3484                 XFS_BUF_DONE(mp->m_sb_bp);
3485                 return (0);
3486         }
3487
3488         /*
3489          * Somebody could've already done the hard work for us.
3490          * No need to get locks for this.
3491          */
3492         if (logerror && log->l_iclog->ic_state & XLOG_STATE_IOERROR) {
3493                 ASSERT(XLOG_FORCED_SHUTDOWN(log));
3494                 return (1);
3495         }
3496         retval = 0;
3497         /*
3498          * We must hold both the GRANT lock and the LOG lock,
3499          * before we mark the filesystem SHUTDOWN and wake
3500          * everybody up to tell the bad news.
3501          */
3502         s = GRANT_LOCK(log);
3503         s2 = LOG_LOCK(log);
3504         mp->m_flags |= XFS_MOUNT_FS_SHUTDOWN;
3505         XFS_BUF_DONE(mp->m_sb_bp);
3506         /*
3507          * This flag is sort of redundant because of the mount flag, but
3508          * it's good to maintain the separation between the log and the rest
3509          * of XFS.
3510          */
3511         log->l_flags |= XLOG_IO_ERROR;
3512
3513         /*
3514          * If we hit a log error, we want to mark all the iclogs IOERROR
3515          * while we're still holding the loglock.
3516          */
3517         if (logerror)
3518                 retval = xlog_state_ioerror(log);
3519         LOG_UNLOCK(log, s2);
3520
3521         /*
3522          * We don't want anybody waiting for log reservations
3523          * after this. That means we have to wake up everybody
3524          * queued up on reserve_headq as well as write_headq.
3525          * In addition, we make sure in xlog_{re}grant_log_space
3526          * that we don't enqueue anything once the SHUTDOWN flag
3527          * is set, and this action is protected by the GRANTLOCK.
3528          */
3529         if ((tic = log->l_reserve_headq)) {
3530                 do {
3531                         sv_signal(&tic->t_sema);
3532                         tic = tic->t_next;
3533                 } while (tic != log->l_reserve_headq);
3534         }
3535
3536         if ((tic = log->l_write_headq)) {
3537                 do {
3538                         sv_signal(&tic->t_sema);
3539                         tic = tic->t_next;
3540                 } while (tic != log->l_write_headq);
3541         }
3542         GRANT_UNLOCK(log, s);
3543
3544         if (! (log->l_iclog->ic_state & XLOG_STATE_IOERROR)) {
3545                 ASSERT(!logerror);
3546                 /*
3547                  * Force the incore logs to disk before shutting the
3548                  * log down completely.
3549                  */
3550                 xlog_state_sync_all(log, XFS_LOG_FORCE|XFS_LOG_SYNC);
3551                 s2 = LOG_LOCK(log);
3552                 retval = xlog_state_ioerror(log);
3553                 LOG_UNLOCK(log, s2);
3554         }
3555         /*
3556          * Wake up everybody waiting on xfs_log_force.
3557          * Callback all log item committed functions as if the
3558          * log writes were completed.
3559          */
3560         xlog_state_do_callback(log, XFS_LI_ABORTED, NULL);
3561
3562 #ifdef XFSERRORDEBUG
3563         {
3564                 xlog_in_core_t  *iclog;
3565
3566                 s = LOG_LOCK(log);
3567                 iclog = log->l_iclog;
3568                 do {
3569                         ASSERT(iclog->ic_callback == 0);
3570                         iclog = iclog->ic_next;
3571                 } while (iclog != log->l_iclog);
3572                 LOG_UNLOCK(log, s);
3573         }
3574 #endif
3575         /* return non-zero if log IOERROR transition had already happened */
3576         return (retval);
3577 }
3578
3579 int
3580 xlog_iclogs_empty(xlog_t *log)
3581 {
3582         xlog_in_core_t  *iclog;
3583
3584         iclog = log->l_iclog;
3585         do {
3586                 /* endianness does not matter here, zero is zero in
3587                  * any language.
3588                  */
3589                 if (iclog->ic_header.h_num_logops)
3590                         return(0);
3591                 iclog = iclog->ic_next;
3592         } while (iclog != log->l_iclog);
3593         return(1);
3594 }