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