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