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