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