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