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