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