linux/drivers/staging/lustre/lustre/obdclass/lu_object.c
<<
>>
Prefs
   1/*
   2 * GPL HEADER START
   3 *
   4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   5 *
   6 * This program is free software; you can redistribute it and/or modify
   7 * it under the terms of the GNU General Public License version 2 only,
   8 * as published by the Free Software Foundation.
   9 *
  10 * This program is distributed in the hope that it will be useful, but
  11 * WITHOUT ANY WARRANTY; without even the implied warranty of
  12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13 * General Public License version 2 for more details (a copy is included
  14 * in the LICENSE file that accompanied this code).
  15 *
  16 * You should have received a copy of the GNU General Public License
  17 * version 2 along with this program; If not, see
  18 * http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
  19 *
  20 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  21 * CA 95054 USA or visit www.sun.com if you need additional information or
  22 * have any questions.
  23 *
  24 * GPL HEADER END
  25 */
  26/*
  27 * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
  28 * Use is subject to license terms.
  29 *
  30 * Copyright (c) 2011, 2012, Intel Corporation.
  31 */
  32/*
  33 * This file is part of Lustre, http://www.lustre.org/
  34 * Lustre is a trademark of Sun Microsystems, Inc.
  35 *
  36 * lustre/obdclass/lu_object.c
  37 *
  38 * Lustre Object.
  39 * These are the only exported functions, they provide some generic
  40 * infrastructure for managing object devices
  41 *
  42 *   Author: Nikita Danilov <nikita.danilov@sun.com>
  43 */
  44
  45#define DEBUG_SUBSYSTEM S_CLASS
  46
  47#include "../../include/linux/libcfs/libcfs.h"
  48
  49# include <linux/module.h>
  50
  51/* hash_long() */
  52#include "../../include/linux/libcfs/libcfs_hash.h"
  53#include "../include/obd_class.h"
  54#include "../include/obd_support.h"
  55#include "../include/lustre_disk.h"
  56#include "../include/lustre_fid.h"
  57#include "../include/lu_object.h"
  58#include "../include/lu_ref.h"
  59#include <linux/list.h>
  60
  61static void lu_object_free(const struct lu_env *env, struct lu_object *o);
  62
  63/**
  64 * Decrease reference counter on object. If last reference is freed, return
  65 * object to the cache, unless lu_object_is_dying(o) holds. In the latter
  66 * case, free object immediately.
  67 */
  68void lu_object_put(const struct lu_env *env, struct lu_object *o)
  69{
  70        struct lu_site_bkt_data *bkt;
  71        struct lu_object_header *top;
  72        struct lu_site    *site;
  73        struct lu_object        *orig;
  74        struct cfs_hash_bd          bd;
  75        const struct lu_fid     *fid;
  76
  77        top  = o->lo_header;
  78        site = o->lo_dev->ld_site;
  79        orig = o;
  80
  81        /*
  82         * till we have full fids-on-OST implemented anonymous objects
  83         * are possible in OSP. such an object isn't listed in the site
  84         * so we should not remove it from the site.
  85         */
  86        fid = lu_object_fid(o);
  87        if (fid_is_zero(fid)) {
  88                LASSERT(top->loh_hash.next == NULL
  89                        && top->loh_hash.pprev == NULL);
  90                LASSERT(list_empty(&top->loh_lru));
  91                if (!atomic_dec_and_test(&top->loh_ref))
  92                        return;
  93                list_for_each_entry_reverse(o, &top->loh_layers, lo_linkage) {
  94                        if (o->lo_ops->loo_object_release != NULL)
  95                                o->lo_ops->loo_object_release(env, o);
  96                }
  97                lu_object_free(env, orig);
  98                return;
  99        }
 100
 101        cfs_hash_bd_get(site->ls_obj_hash, &top->loh_fid, &bd);
 102        bkt = cfs_hash_bd_extra_get(site->ls_obj_hash, &bd);
 103
 104        if (!cfs_hash_bd_dec_and_lock(site->ls_obj_hash, &bd, &top->loh_ref)) {
 105                if (lu_object_is_dying(top)) {
 106
 107                        /*
 108                         * somebody may be waiting for this, currently only
 109                         * used for cl_object, see cl_object_put_last().
 110                         */
 111                        wake_up_all(&bkt->lsb_marche_funebre);
 112                }
 113                return;
 114        }
 115
 116        LASSERT(bkt->lsb_busy > 0);
 117        bkt->lsb_busy--;
 118        /*
 119         * When last reference is released, iterate over object
 120         * layers, and notify them that object is no longer busy.
 121         */
 122        list_for_each_entry_reverse(o, &top->loh_layers, lo_linkage) {
 123                if (o->lo_ops->loo_object_release != NULL)
 124                        o->lo_ops->loo_object_release(env, o);
 125        }
 126
 127        if (!lu_object_is_dying(top)) {
 128                LASSERT(list_empty(&top->loh_lru));
 129                list_add_tail(&top->loh_lru, &bkt->lsb_lru);
 130                cfs_hash_bd_unlock(site->ls_obj_hash, &bd, 1);
 131                return;
 132        }
 133
 134        /*
 135         * If object is dying (will not be cached), removed it
 136         * from hash table and LRU.
 137         *
 138         * This is done with hash table and LRU lists locked. As the only
 139         * way to acquire first reference to previously unreferenced
 140         * object is through hash-table lookup (lu_object_find()),
 141         * or LRU scanning (lu_site_purge()), that are done under hash-table
 142         * and LRU lock, no race with concurrent object lookup is possible
 143         * and we can safely destroy object below.
 144         */
 145        if (!test_and_set_bit(LU_OBJECT_UNHASHED, &top->loh_flags))
 146                cfs_hash_bd_del_locked(site->ls_obj_hash, &bd, &top->loh_hash);
 147        cfs_hash_bd_unlock(site->ls_obj_hash, &bd, 1);
 148        /*
 149         * Object was already removed from hash and lru above, can
 150         * kill it.
 151         */
 152        lu_object_free(env, orig);
 153}
 154EXPORT_SYMBOL(lu_object_put);
 155
 156/**
 157 * Put object and don't keep in cache. This is temporary solution for
 158 * multi-site objects when its layering is not constant.
 159 */
 160void lu_object_put_nocache(const struct lu_env *env, struct lu_object *o)
 161{
 162        set_bit(LU_OBJECT_HEARD_BANSHEE, &o->lo_header->loh_flags);
 163        return lu_object_put(env, o);
 164}
 165EXPORT_SYMBOL(lu_object_put_nocache);
 166
 167/**
 168 * Kill the object and take it out of LRU cache.
 169 * Currently used by client code for layout change.
 170 */
 171void lu_object_unhash(const struct lu_env *env, struct lu_object *o)
 172{
 173        struct lu_object_header *top;
 174
 175        top = o->lo_header;
 176        set_bit(LU_OBJECT_HEARD_BANSHEE, &top->loh_flags);
 177        if (!test_and_set_bit(LU_OBJECT_UNHASHED, &top->loh_flags)) {
 178                struct cfs_hash *obj_hash = o->lo_dev->ld_site->ls_obj_hash;
 179                struct cfs_hash_bd bd;
 180
 181                cfs_hash_bd_get_and_lock(obj_hash, &top->loh_fid, &bd, 1);
 182                list_del_init(&top->loh_lru);
 183                cfs_hash_bd_del_locked(obj_hash, &bd, &top->loh_hash);
 184                cfs_hash_bd_unlock(obj_hash, &bd, 1);
 185        }
 186}
 187EXPORT_SYMBOL(lu_object_unhash);
 188
 189/**
 190 * Allocate new object.
 191 *
 192 * This follows object creation protocol, described in the comment within
 193 * struct lu_device_operations definition.
 194 */
 195static struct lu_object *lu_object_alloc(const struct lu_env *env,
 196                                         struct lu_device *dev,
 197                                         const struct lu_fid *f,
 198                                         const struct lu_object_conf *conf)
 199{
 200        struct lu_object *scan;
 201        struct lu_object *top;
 202        struct list_head *layers;
 203        unsigned int init_mask = 0;
 204        unsigned int init_flag;
 205        int clean;
 206        int result;
 207
 208        /*
 209         * Create top-level object slice. This will also create
 210         * lu_object_header.
 211         */
 212        top = dev->ld_ops->ldo_object_alloc(env, NULL, dev);
 213        if (top == NULL)
 214                return ERR_PTR(-ENOMEM);
 215        if (IS_ERR(top))
 216                return top;
 217        /*
 218         * This is the only place where object fid is assigned. It's constant
 219         * after this point.
 220         */
 221        top->lo_header->loh_fid = *f;
 222        layers = &top->lo_header->loh_layers;
 223
 224        do {
 225                /*
 226                 * Call ->loo_object_init() repeatedly, until no more new
 227                 * object slices are created.
 228                 */
 229                clean = 1;
 230                init_flag = 1;
 231                list_for_each_entry(scan, layers, lo_linkage) {
 232                        if (init_mask & init_flag)
 233                                goto next;
 234                        clean = 0;
 235                        scan->lo_header = top->lo_header;
 236                        result = scan->lo_ops->loo_object_init(env, scan, conf);
 237                        if (result != 0) {
 238                                lu_object_free(env, top);
 239                                return ERR_PTR(result);
 240                        }
 241                        init_mask |= init_flag;
 242next:
 243                        init_flag <<= 1;
 244                }
 245        } while (!clean);
 246
 247        list_for_each_entry_reverse(scan, layers, lo_linkage) {
 248                if (scan->lo_ops->loo_object_start != NULL) {
 249                        result = scan->lo_ops->loo_object_start(env, scan);
 250                        if (result != 0) {
 251                                lu_object_free(env, top);
 252                                return ERR_PTR(result);
 253                        }
 254                }
 255        }
 256
 257        lprocfs_counter_incr(dev->ld_site->ls_stats, LU_SS_CREATED);
 258        return top;
 259}
 260
 261/**
 262 * Free an object.
 263 */
 264static void lu_object_free(const struct lu_env *env, struct lu_object *o)
 265{
 266        struct lu_site_bkt_data *bkt;
 267        struct lu_site    *site;
 268        struct lu_object        *scan;
 269        struct list_head              *layers;
 270        struct list_head               splice;
 271
 272        site   = o->lo_dev->ld_site;
 273        layers = &o->lo_header->loh_layers;
 274        bkt    = lu_site_bkt_from_fid(site, &o->lo_header->loh_fid);
 275        /*
 276         * First call ->loo_object_delete() method to release all resources.
 277         */
 278        list_for_each_entry_reverse(scan, layers, lo_linkage) {
 279                if (scan->lo_ops->loo_object_delete != NULL)
 280                        scan->lo_ops->loo_object_delete(env, scan);
 281        }
 282
 283        /*
 284         * Then, splice object layers into stand-alone list, and call
 285         * ->loo_object_free() on all layers to free memory. Splice is
 286         * necessary, because lu_object_header is freed together with the
 287         * top-level slice.
 288         */
 289        INIT_LIST_HEAD(&splice);
 290        list_splice_init(layers, &splice);
 291        while (!list_empty(&splice)) {
 292                /*
 293                 * Free layers in bottom-to-top order, so that object header
 294                 * lives as long as possible and ->loo_object_free() methods
 295                 * can look at its contents.
 296                 */
 297                o = container_of0(splice.prev, struct lu_object, lo_linkage);
 298                list_del_init(&o->lo_linkage);
 299                LASSERT(o->lo_ops->loo_object_free != NULL);
 300                o->lo_ops->loo_object_free(env, o);
 301        }
 302
 303        if (waitqueue_active(&bkt->lsb_marche_funebre))
 304                wake_up_all(&bkt->lsb_marche_funebre);
 305}
 306
 307/**
 308 * Free \a nr objects from the cold end of the site LRU list.
 309 */
 310int lu_site_purge(const struct lu_env *env, struct lu_site *s, int nr)
 311{
 312        struct lu_object_header *h;
 313        struct lu_object_header *temp;
 314        struct lu_site_bkt_data *bkt;
 315        struct cfs_hash_bd          bd;
 316        struct cfs_hash_bd          bd2;
 317        struct list_head               dispose;
 318        int                   did_sth;
 319        int                   start;
 320        int                   count;
 321        int                   bnr;
 322        int                   i;
 323
 324        if (OBD_FAIL_CHECK(OBD_FAIL_OBD_NO_LRU))
 325                return 0;
 326
 327        INIT_LIST_HEAD(&dispose);
 328        /*
 329         * Under LRU list lock, scan LRU list and move unreferenced objects to
 330         * the dispose list, removing them from LRU and hash table.
 331         */
 332        start = s->ls_purge_start;
 333        bnr = (nr == ~0) ? -1 : nr / CFS_HASH_NBKT(s->ls_obj_hash) + 1;
 334 again:
 335        did_sth = 0;
 336        cfs_hash_for_each_bucket(s->ls_obj_hash, &bd, i) {
 337                if (i < start)
 338                        continue;
 339                count = bnr;
 340                cfs_hash_bd_lock(s->ls_obj_hash, &bd, 1);
 341                bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, &bd);
 342
 343                list_for_each_entry_safe(h, temp, &bkt->lsb_lru, loh_lru) {
 344                        LASSERT(atomic_read(&h->loh_ref) == 0);
 345
 346                        cfs_hash_bd_get(s->ls_obj_hash, &h->loh_fid, &bd2);
 347                        LASSERT(bd.bd_bucket == bd2.bd_bucket);
 348
 349                        cfs_hash_bd_del_locked(s->ls_obj_hash,
 350                                               &bd2, &h->loh_hash);
 351                        list_move(&h->loh_lru, &dispose);
 352                        if (did_sth == 0)
 353                                did_sth = 1;
 354
 355                        if (nr != ~0 && --nr == 0)
 356                                break;
 357
 358                        if (count > 0 && --count == 0)
 359                                break;
 360
 361                }
 362                cfs_hash_bd_unlock(s->ls_obj_hash, &bd, 1);
 363                cond_resched();
 364                /*
 365                 * Free everything on the dispose list. This is safe against
 366                 * races due to the reasons described in lu_object_put().
 367                 */
 368                while (!list_empty(&dispose)) {
 369                        h = container_of0(dispose.next,
 370                                          struct lu_object_header, loh_lru);
 371                        list_del_init(&h->loh_lru);
 372                        lu_object_free(env, lu_object_top(h));
 373                        lprocfs_counter_incr(s->ls_stats, LU_SS_LRU_PURGED);
 374                }
 375
 376                if (nr == 0)
 377                        break;
 378        }
 379
 380        if (nr != 0 && did_sth && start != 0) {
 381                start = 0; /* restart from the first bucket */
 382                goto again;
 383        }
 384        /* race on s->ls_purge_start, but nobody cares */
 385        s->ls_purge_start = i % CFS_HASH_NBKT(s->ls_obj_hash);
 386
 387        return nr;
 388}
 389EXPORT_SYMBOL(lu_site_purge);
 390
 391/*
 392 * Object printing.
 393 *
 394 * Code below has to jump through certain loops to output object description
 395 * into libcfs_debug_msg-based log. The problem is that lu_object_print()
 396 * composes object description from strings that are parts of _lines_ of
 397 * output (i.e., strings that are not terminated by newline). This doesn't fit
 398 * very well into libcfs_debug_msg() interface that assumes that each message
 399 * supplied to it is a self-contained output line.
 400 *
 401 * To work around this, strings are collected in a temporary buffer
 402 * (implemented as a value of lu_cdebug_key key), until terminating newline
 403 * character is detected.
 404 *
 405 */
 406
 407enum {
 408        /**
 409         * Maximal line size.
 410         *
 411         * XXX overflow is not handled correctly.
 412         */
 413        LU_CDEBUG_LINE = 512
 414};
 415
 416struct lu_cdebug_data {
 417        /**
 418         * Temporary buffer.
 419         */
 420        char lck_area[LU_CDEBUG_LINE];
 421};
 422
 423/* context key constructor/destructor: lu_global_key_init, lu_global_key_fini */
 424LU_KEY_INIT_FINI(lu_global, struct lu_cdebug_data);
 425
 426/**
 427 * Key, holding temporary buffer. This key is registered very early by
 428 * lu_global_init().
 429 */
 430struct lu_context_key lu_global_key = {
 431        .lct_tags = LCT_MD_THREAD | LCT_DT_THREAD |
 432                    LCT_MG_THREAD | LCT_CL_THREAD | LCT_LOCAL,
 433        .lct_init = lu_global_key_init,
 434        .lct_fini = lu_global_key_fini
 435};
 436
 437/**
 438 * Printer function emitting messages through libcfs_debug_msg().
 439 */
 440int lu_cdebug_printer(const struct lu_env *env,
 441                      void *cookie, const char *format, ...)
 442{
 443        struct libcfs_debug_msg_data *msgdata = cookie;
 444        struct lu_cdebug_data   *key;
 445        int used;
 446        int complete;
 447        va_list args;
 448
 449        va_start(args, format);
 450
 451        key = lu_context_key_get(&env->le_ctx, &lu_global_key);
 452        LASSERT(key != NULL);
 453
 454        used = strlen(key->lck_area);
 455        complete = format[strlen(format) - 1] == '\n';
 456        /*
 457         * Append new chunk to the buffer.
 458         */
 459        vsnprintf(key->lck_area + used,
 460                  ARRAY_SIZE(key->lck_area) - used, format, args);
 461        if (complete) {
 462                if (cfs_cdebug_show(msgdata->msg_mask, msgdata->msg_subsys))
 463                        libcfs_debug_msg(msgdata, "%s", key->lck_area);
 464                key->lck_area[0] = 0;
 465        }
 466        va_end(args);
 467        return 0;
 468}
 469EXPORT_SYMBOL(lu_cdebug_printer);
 470
 471/**
 472 * Print object header.
 473 */
 474void lu_object_header_print(const struct lu_env *env, void *cookie,
 475                            lu_printer_t printer,
 476                            const struct lu_object_header *hdr)
 477{
 478        (*printer)(env, cookie, "header@%p[%#lx, %d, "DFID"%s%s%s]",
 479                   hdr, hdr->loh_flags, atomic_read(&hdr->loh_ref),
 480                   PFID(&hdr->loh_fid),
 481                   hlist_unhashed(&hdr->loh_hash) ? "" : " hash",
 482                   list_empty((struct list_head *)&hdr->loh_lru) ? \
 483                   "" : " lru",
 484                   hdr->loh_attr & LOHA_EXISTS ? " exist":"");
 485}
 486EXPORT_SYMBOL(lu_object_header_print);
 487
 488/**
 489 * Print human readable representation of the \a o to the \a printer.
 490 */
 491void lu_object_print(const struct lu_env *env, void *cookie,
 492                     lu_printer_t printer, const struct lu_object *o)
 493{
 494        static const char ruler[] = "........................................";
 495        struct lu_object_header *top;
 496        int depth = 4;
 497
 498        top = o->lo_header;
 499        lu_object_header_print(env, cookie, printer, top);
 500        (*printer)(env, cookie, "{\n");
 501
 502        list_for_each_entry(o, &top->loh_layers, lo_linkage) {
 503                /*
 504                 * print `.' \a depth times followed by type name and address
 505                 */
 506                (*printer)(env, cookie, "%*.*s%s@%p", depth, depth, ruler,
 507                           o->lo_dev->ld_type->ldt_name, o);
 508
 509                if (o->lo_ops->loo_object_print != NULL)
 510                        (*o->lo_ops->loo_object_print)(env, cookie, printer, o);
 511
 512                (*printer)(env, cookie, "\n");
 513        }
 514
 515        (*printer)(env, cookie, "} header@%p\n", top);
 516}
 517EXPORT_SYMBOL(lu_object_print);
 518
 519/**
 520 * Check object consistency.
 521 */
 522int lu_object_invariant(const struct lu_object *o)
 523{
 524        struct lu_object_header *top;
 525
 526        top = o->lo_header;
 527        list_for_each_entry(o, &top->loh_layers, lo_linkage) {
 528                if (o->lo_ops->loo_object_invariant != NULL &&
 529                    !o->lo_ops->loo_object_invariant(o))
 530                        return 0;
 531        }
 532        return 1;
 533}
 534EXPORT_SYMBOL(lu_object_invariant);
 535
 536static struct lu_object *htable_lookup(struct lu_site *s,
 537                                       struct cfs_hash_bd *bd,
 538                                       const struct lu_fid *f,
 539                                       wait_queue_t *waiter,
 540                                       __u64 *version)
 541{
 542        struct lu_site_bkt_data *bkt;
 543        struct lu_object_header *h;
 544        struct hlist_node       *hnode;
 545        __u64  ver = cfs_hash_bd_version_get(bd);
 546
 547        if (*version == ver)
 548                return ERR_PTR(-ENOENT);
 549
 550        *version = ver;
 551        bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, bd);
 552        /* cfs_hash_bd_peek_locked is a somehow "internal" function
 553         * of cfs_hash, it doesn't add refcount on object. */
 554        hnode = cfs_hash_bd_peek_locked(s->ls_obj_hash, bd, (void *)f);
 555        if (hnode == NULL) {
 556                lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_MISS);
 557                return ERR_PTR(-ENOENT);
 558        }
 559
 560        h = container_of0(hnode, struct lu_object_header, loh_hash);
 561        if (likely(!lu_object_is_dying(h))) {
 562                cfs_hash_get(s->ls_obj_hash, hnode);
 563                lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_HIT);
 564                list_del_init(&h->loh_lru);
 565                return lu_object_top(h);
 566        }
 567
 568        /*
 569         * Lookup found an object being destroyed this object cannot be
 570         * returned (to assure that references to dying objects are eventually
 571         * drained), and moreover, lookup has to wait until object is freed.
 572         */
 573
 574        init_waitqueue_entry(waiter, current);
 575        add_wait_queue(&bkt->lsb_marche_funebre, waiter);
 576        set_current_state(TASK_UNINTERRUPTIBLE);
 577        lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_DEATH_RACE);
 578        return ERR_PTR(-EAGAIN);
 579}
 580
 581/**
 582 * Search cache for an object with the fid \a f. If such object is found,
 583 * return it. Otherwise, create new object, insert it into cache and return
 584 * it. In any case, additional reference is acquired on the returned object.
 585 */
 586struct lu_object *lu_object_find(const struct lu_env *env,
 587                                 struct lu_device *dev, const struct lu_fid *f,
 588                                 const struct lu_object_conf *conf)
 589{
 590        return lu_object_find_at(env, dev->ld_site->ls_top_dev, f, conf);
 591}
 592EXPORT_SYMBOL(lu_object_find);
 593
 594static struct lu_object *lu_object_new(const struct lu_env *env,
 595                                       struct lu_device *dev,
 596                                       const struct lu_fid *f,
 597                                       const struct lu_object_conf *conf)
 598{
 599        struct lu_object        *o;
 600        struct cfs_hash       *hs;
 601        struct cfs_hash_bd          bd;
 602        struct lu_site_bkt_data *bkt;
 603
 604        o = lu_object_alloc(env, dev, f, conf);
 605        if (unlikely(IS_ERR(o)))
 606                return o;
 607
 608        hs = dev->ld_site->ls_obj_hash;
 609        cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
 610        bkt = cfs_hash_bd_extra_get(hs, &bd);
 611        cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
 612        bkt->lsb_busy++;
 613        cfs_hash_bd_unlock(hs, &bd, 1);
 614        return o;
 615}
 616
 617/**
 618 * Core logic of lu_object_find*() functions.
 619 */
 620static struct lu_object *lu_object_find_try(const struct lu_env *env,
 621                                            struct lu_device *dev,
 622                                            const struct lu_fid *f,
 623                                            const struct lu_object_conf *conf,
 624                                            wait_queue_t *waiter)
 625{
 626        struct lu_object      *o;
 627        struct lu_object      *shadow;
 628        struct lu_site  *s;
 629        struct cfs_hash     *hs;
 630        struct cfs_hash_bd        bd;
 631        __u64             version = 0;
 632
 633        /*
 634         * This uses standard index maintenance protocol:
 635         *
 636         *     - search index under lock, and return object if found;
 637         *     - otherwise, unlock index, allocate new object;
 638         *     - lock index and search again;
 639         *     - if nothing is found (usual case), insert newly created
 640         *       object into index;
 641         *     - otherwise (race: other thread inserted object), free
 642         *       object just allocated.
 643         *     - unlock index;
 644         *     - return object.
 645         *
 646         * For "LOC_F_NEW" case, we are sure the object is new established.
 647         * It is unnecessary to perform lookup-alloc-lookup-insert, instead,
 648         * just alloc and insert directly.
 649         *
 650         * If dying object is found during index search, add @waiter to the
 651         * site wait-queue and return ERR_PTR(-EAGAIN).
 652         */
 653        if (conf != NULL && conf->loc_flags & LOC_F_NEW)
 654                return lu_object_new(env, dev, f, conf);
 655
 656        s  = dev->ld_site;
 657        hs = s->ls_obj_hash;
 658        cfs_hash_bd_get_and_lock(hs, (void *)f, &bd, 1);
 659        o = htable_lookup(s, &bd, f, waiter, &version);
 660        cfs_hash_bd_unlock(hs, &bd, 1);
 661        if (!IS_ERR(o) || PTR_ERR(o) != -ENOENT)
 662                return o;
 663
 664        /*
 665         * Allocate new object. This may result in rather complicated
 666         * operations, including fld queries, inode loading, etc.
 667         */
 668        o = lu_object_alloc(env, dev, f, conf);
 669        if (unlikely(IS_ERR(o)))
 670                return o;
 671
 672        LASSERT(lu_fid_eq(lu_object_fid(o), f));
 673
 674        cfs_hash_bd_lock(hs, &bd, 1);
 675
 676        shadow = htable_lookup(s, &bd, f, waiter, &version);
 677        if (likely(IS_ERR(shadow) && PTR_ERR(shadow) == -ENOENT)) {
 678                struct lu_site_bkt_data *bkt;
 679
 680                bkt = cfs_hash_bd_extra_get(hs, &bd);
 681                cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
 682                bkt->lsb_busy++;
 683                cfs_hash_bd_unlock(hs, &bd, 1);
 684                return o;
 685        }
 686
 687        lprocfs_counter_incr(s->ls_stats, LU_SS_CACHE_RACE);
 688        cfs_hash_bd_unlock(hs, &bd, 1);
 689        lu_object_free(env, o);
 690        return shadow;
 691}
 692
 693/**
 694 * Much like lu_object_find(), but top level device of object is specifically
 695 * \a dev rather than top level device of the site. This interface allows
 696 * objects of different "stacking" to be created within the same site.
 697 */
 698struct lu_object *lu_object_find_at(const struct lu_env *env,
 699                                    struct lu_device *dev,
 700                                    const struct lu_fid *f,
 701                                    const struct lu_object_conf *conf)
 702{
 703        struct lu_site_bkt_data *bkt;
 704        struct lu_object        *obj;
 705        wait_queue_t       wait;
 706
 707        while (1) {
 708                obj = lu_object_find_try(env, dev, f, conf, &wait);
 709                if (obj != ERR_PTR(-EAGAIN))
 710                        return obj;
 711                /*
 712                 * lu_object_find_try() already added waiter into the
 713                 * wait queue.
 714                 */
 715                schedule();
 716                bkt = lu_site_bkt_from_fid(dev->ld_site, (void *)f);
 717                remove_wait_queue(&bkt->lsb_marche_funebre, &wait);
 718        }
 719}
 720EXPORT_SYMBOL(lu_object_find_at);
 721
 722/**
 723 * Find object with given fid, and return its slice belonging to given device.
 724 */
 725struct lu_object *lu_object_find_slice(const struct lu_env *env,
 726                                       struct lu_device *dev,
 727                                       const struct lu_fid *f,
 728                                       const struct lu_object_conf *conf)
 729{
 730        struct lu_object *top;
 731        struct lu_object *obj;
 732
 733        top = lu_object_find(env, dev, f, conf);
 734        if (!IS_ERR(top)) {
 735                obj = lu_object_locate(top->lo_header, dev->ld_type);
 736                if (obj == NULL)
 737                        lu_object_put(env, top);
 738        } else
 739                obj = top;
 740        return obj;
 741}
 742EXPORT_SYMBOL(lu_object_find_slice);
 743
 744/**
 745 * Global list of all device types.
 746 */
 747static LIST_HEAD(lu_device_types);
 748
 749int lu_device_type_init(struct lu_device_type *ldt)
 750{
 751        int result = 0;
 752
 753        INIT_LIST_HEAD(&ldt->ldt_linkage);
 754        if (ldt->ldt_ops->ldto_init)
 755                result = ldt->ldt_ops->ldto_init(ldt);
 756        if (result == 0)
 757                list_add(&ldt->ldt_linkage, &lu_device_types);
 758        return result;
 759}
 760EXPORT_SYMBOL(lu_device_type_init);
 761
 762void lu_device_type_fini(struct lu_device_type *ldt)
 763{
 764        list_del_init(&ldt->ldt_linkage);
 765        if (ldt->ldt_ops->ldto_fini)
 766                ldt->ldt_ops->ldto_fini(ldt);
 767}
 768EXPORT_SYMBOL(lu_device_type_fini);
 769
 770void lu_types_stop(void)
 771{
 772        struct lu_device_type *ldt;
 773
 774        list_for_each_entry(ldt, &lu_device_types, ldt_linkage) {
 775                if (ldt->ldt_device_nr == 0 && ldt->ldt_ops->ldto_stop)
 776                        ldt->ldt_ops->ldto_stop(ldt);
 777        }
 778}
 779EXPORT_SYMBOL(lu_types_stop);
 780
 781/**
 782 * Global list of all sites on this node
 783 */
 784static LIST_HEAD(lu_sites);
 785static DEFINE_MUTEX(lu_sites_guard);
 786
 787/**
 788 * Global environment used by site shrinker.
 789 */
 790static struct lu_env lu_shrink_env;
 791
 792struct lu_site_print_arg {
 793        struct lu_env   *lsp_env;
 794        void        *lsp_cookie;
 795        lu_printer_t     lsp_printer;
 796};
 797
 798static int
 799lu_site_obj_print(struct cfs_hash *hs, struct cfs_hash_bd *bd,
 800                  struct hlist_node *hnode, void *data)
 801{
 802        struct lu_site_print_arg *arg = (struct lu_site_print_arg *)data;
 803        struct lu_object_header  *h;
 804
 805        h = hlist_entry(hnode, struct lu_object_header, loh_hash);
 806        if (!list_empty(&h->loh_layers)) {
 807                const struct lu_object *o;
 808
 809                o = lu_object_top(h);
 810                lu_object_print(arg->lsp_env, arg->lsp_cookie,
 811                                arg->lsp_printer, o);
 812        } else {
 813                lu_object_header_print(arg->lsp_env, arg->lsp_cookie,
 814                                       arg->lsp_printer, h);
 815        }
 816        return 0;
 817}
 818
 819/**
 820 * Print all objects in \a s.
 821 */
 822void lu_site_print(const struct lu_env *env, struct lu_site *s, void *cookie,
 823                   lu_printer_t printer)
 824{
 825        struct lu_site_print_arg arg = {
 826                .lsp_env     = (struct lu_env *)env,
 827                .lsp_cookie  = cookie,
 828                .lsp_printer = printer,
 829        };
 830
 831        cfs_hash_for_each(s->ls_obj_hash, lu_site_obj_print, &arg);
 832}
 833EXPORT_SYMBOL(lu_site_print);
 834
 835enum {
 836        LU_CACHE_PERCENT_MAX     = 50,
 837        LU_CACHE_PERCENT_DEFAULT = 20
 838};
 839
 840static unsigned int lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
 841module_param(lu_cache_percent, int, 0644);
 842MODULE_PARM_DESC(lu_cache_percent, "Percentage of memory to be used as lu_object cache");
 843
 844/**
 845 * Return desired hash table order.
 846 */
 847static int lu_htable_order(void)
 848{
 849        unsigned long cache_size;
 850        int bits;
 851
 852        /*
 853         * Calculate hash table size, assuming that we want reasonable
 854         * performance when 20% of total memory is occupied by cache of
 855         * lu_objects.
 856         *
 857         * Size of lu_object is (arbitrary) taken as 1K (together with inode).
 858         */
 859        cache_size = totalram_pages;
 860
 861#if BITS_PER_LONG == 32
 862        /* limit hashtable size for lowmem systems to low RAM */
 863        if (cache_size > 1 << (30 - PAGE_CACHE_SHIFT))
 864                cache_size = 1 << (30 - PAGE_CACHE_SHIFT) * 3 / 4;
 865#endif
 866
 867        /* clear off unreasonable cache setting. */
 868        if (lu_cache_percent == 0 || lu_cache_percent > LU_CACHE_PERCENT_MAX) {
 869                CWARN("obdclass: invalid lu_cache_percent: %u, it must be in the range of (0, %u]. Will use default value: %u.\n",
 870                      lu_cache_percent, LU_CACHE_PERCENT_MAX,
 871                      LU_CACHE_PERCENT_DEFAULT);
 872
 873                lu_cache_percent = LU_CACHE_PERCENT_DEFAULT;
 874        }
 875        cache_size = cache_size / 100 * lu_cache_percent *
 876                (PAGE_CACHE_SIZE / 1024);
 877
 878        for (bits = 1; (1 << bits) < cache_size; ++bits) {
 879                ;
 880        }
 881        return bits;
 882}
 883
 884static unsigned lu_obj_hop_hash(struct cfs_hash *hs,
 885                                const void *key, unsigned mask)
 886{
 887        struct lu_fid  *fid = (struct lu_fid *)key;
 888        __u32      hash;
 889
 890        hash = fid_flatten32(fid);
 891        hash += (hash >> 4) + (hash << 12); /* mixing oid and seq */
 892        hash = hash_long(hash, hs->hs_bkt_bits);
 893
 894        /* give me another random factor */
 895        hash -= hash_long((unsigned long)hs, fid_oid(fid) % 11 + 3);
 896
 897        hash <<= hs->hs_cur_bits - hs->hs_bkt_bits;
 898        hash |= (fid_seq(fid) + fid_oid(fid)) & (CFS_HASH_NBKT(hs) - 1);
 899
 900        return hash & mask;
 901}
 902
 903static void *lu_obj_hop_object(struct hlist_node *hnode)
 904{
 905        return hlist_entry(hnode, struct lu_object_header, loh_hash);
 906}
 907
 908static void *lu_obj_hop_key(struct hlist_node *hnode)
 909{
 910        struct lu_object_header *h;
 911
 912        h = hlist_entry(hnode, struct lu_object_header, loh_hash);
 913        return &h->loh_fid;
 914}
 915
 916static int lu_obj_hop_keycmp(const void *key, struct hlist_node *hnode)
 917{
 918        struct lu_object_header *h;
 919
 920        h = hlist_entry(hnode, struct lu_object_header, loh_hash);
 921        return lu_fid_eq(&h->loh_fid, (struct lu_fid *)key);
 922}
 923
 924static void lu_obj_hop_get(struct cfs_hash *hs, struct hlist_node *hnode)
 925{
 926        struct lu_object_header *h;
 927
 928        h = hlist_entry(hnode, struct lu_object_header, loh_hash);
 929        if (atomic_add_return(1, &h->loh_ref) == 1) {
 930                struct lu_site_bkt_data *bkt;
 931                struct cfs_hash_bd          bd;
 932
 933                cfs_hash_bd_get(hs, &h->loh_fid, &bd);
 934                bkt = cfs_hash_bd_extra_get(hs, &bd);
 935                bkt->lsb_busy++;
 936        }
 937}
 938
 939static void lu_obj_hop_put_locked(struct cfs_hash *hs, struct hlist_node *hnode)
 940{
 941        LBUG(); /* we should never called it */
 942}
 943
 944cfs_hash_ops_t lu_site_hash_ops = {
 945        .hs_hash        = lu_obj_hop_hash,
 946        .hs_key  = lu_obj_hop_key,
 947        .hs_keycmp      = lu_obj_hop_keycmp,
 948        .hs_object      = lu_obj_hop_object,
 949        .hs_get  = lu_obj_hop_get,
 950        .hs_put_locked  = lu_obj_hop_put_locked,
 951};
 952
 953void lu_dev_add_linkage(struct lu_site *s, struct lu_device *d)
 954{
 955        spin_lock(&s->ls_ld_lock);
 956        if (list_empty(&d->ld_linkage))
 957                list_add(&d->ld_linkage, &s->ls_ld_linkage);
 958        spin_unlock(&s->ls_ld_lock);
 959}
 960EXPORT_SYMBOL(lu_dev_add_linkage);
 961
 962void lu_dev_del_linkage(struct lu_site *s, struct lu_device *d)
 963{
 964        spin_lock(&s->ls_ld_lock);
 965        list_del_init(&d->ld_linkage);
 966        spin_unlock(&s->ls_ld_lock);
 967}
 968EXPORT_SYMBOL(lu_dev_del_linkage);
 969
 970/**
 971 * Initialize site \a s, with \a d as the top level device.
 972 */
 973#define LU_SITE_BITS_MIN    12
 974#define LU_SITE_BITS_MAX    24
 975/**
 976 * total 256 buckets, we don't want too many buckets because:
 977 * - consume too much memory
 978 * - avoid unbalanced LRU list
 979 */
 980#define LU_SITE_BKT_BITS    8
 981
 982int lu_site_init(struct lu_site *s, struct lu_device *top)
 983{
 984        struct lu_site_bkt_data *bkt;
 985        struct cfs_hash_bd bd;
 986        char name[16];
 987        int bits;
 988        int i;
 989
 990        memset(s, 0, sizeof(*s));
 991        bits = lu_htable_order();
 992        snprintf(name, 16, "lu_site_%s", top->ld_type->ldt_name);
 993        for (bits = min(max(LU_SITE_BITS_MIN, bits), LU_SITE_BITS_MAX);
 994             bits >= LU_SITE_BITS_MIN; bits--) {
 995                s->ls_obj_hash = cfs_hash_create(name, bits, bits,
 996                                                 bits - LU_SITE_BKT_BITS,
 997                                                 sizeof(*bkt), 0, 0,
 998                                                 &lu_site_hash_ops,
 999                                                 CFS_HASH_SPIN_BKTLOCK |
1000                                                 CFS_HASH_NO_ITEMREF |
1001                                                 CFS_HASH_DEPTH |
1002                                                 CFS_HASH_ASSERT_EMPTY);
1003                if (s->ls_obj_hash != NULL)
1004                        break;
1005        }
1006
1007        if (s->ls_obj_hash == NULL) {
1008                CERROR("failed to create lu_site hash with bits: %d\n", bits);
1009                return -ENOMEM;
1010        }
1011
1012        cfs_hash_for_each_bucket(s->ls_obj_hash, &bd, i) {
1013                bkt = cfs_hash_bd_extra_get(s->ls_obj_hash, &bd);
1014                INIT_LIST_HEAD(&bkt->lsb_lru);
1015                init_waitqueue_head(&bkt->lsb_marche_funebre);
1016        }
1017
1018        s->ls_stats = lprocfs_alloc_stats(LU_SS_LAST_STAT, 0);
1019        if (s->ls_stats == NULL) {
1020                cfs_hash_putref(s->ls_obj_hash);
1021                s->ls_obj_hash = NULL;
1022                return -ENOMEM;
1023        }
1024
1025        lprocfs_counter_init(s->ls_stats, LU_SS_CREATED,
1026                             0, "created", "created");
1027        lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_HIT,
1028                             0, "cache_hit", "cache_hit");
1029        lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_MISS,
1030                             0, "cache_miss", "cache_miss");
1031        lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_RACE,
1032                             0, "cache_race", "cache_race");
1033        lprocfs_counter_init(s->ls_stats, LU_SS_CACHE_DEATH_RACE,
1034                             0, "cache_death_race", "cache_death_race");
1035        lprocfs_counter_init(s->ls_stats, LU_SS_LRU_PURGED,
1036                             0, "lru_purged", "lru_purged");
1037
1038        INIT_LIST_HEAD(&s->ls_linkage);
1039        s->ls_top_dev = top;
1040        top->ld_site = s;
1041        lu_device_get(top);
1042        lu_ref_add(&top->ld_reference, "site-top", s);
1043
1044        INIT_LIST_HEAD(&s->ls_ld_linkage);
1045        spin_lock_init(&s->ls_ld_lock);
1046
1047        lu_dev_add_linkage(s, top);
1048
1049        return 0;
1050}
1051EXPORT_SYMBOL(lu_site_init);
1052
1053/**
1054 * Finalize \a s and release its resources.
1055 */
1056void lu_site_fini(struct lu_site *s)
1057{
1058        mutex_lock(&lu_sites_guard);
1059        list_del_init(&s->ls_linkage);
1060        mutex_unlock(&lu_sites_guard);
1061
1062        if (s->ls_obj_hash != NULL) {
1063                cfs_hash_putref(s->ls_obj_hash);
1064                s->ls_obj_hash = NULL;
1065        }
1066
1067        if (s->ls_top_dev != NULL) {
1068                s->ls_top_dev->ld_site = NULL;
1069                lu_ref_del(&s->ls_top_dev->ld_reference, "site-top", s);
1070                lu_device_put(s->ls_top_dev);
1071                s->ls_top_dev = NULL;
1072        }
1073
1074        if (s->ls_stats != NULL)
1075                lprocfs_free_stats(&s->ls_stats);
1076}
1077EXPORT_SYMBOL(lu_site_fini);
1078
1079/**
1080 * Called when initialization of stack for this site is completed.
1081 */
1082int lu_site_init_finish(struct lu_site *s)
1083{
1084        int result;
1085        mutex_lock(&lu_sites_guard);
1086        result = lu_context_refill(&lu_shrink_env.le_ctx);
1087        if (result == 0)
1088                list_add(&s->ls_linkage, &lu_sites);
1089        mutex_unlock(&lu_sites_guard);
1090        return result;
1091}
1092EXPORT_SYMBOL(lu_site_init_finish);
1093
1094/**
1095 * Acquire additional reference on device \a d
1096 */
1097void lu_device_get(struct lu_device *d)
1098{
1099        atomic_inc(&d->ld_ref);
1100}
1101EXPORT_SYMBOL(lu_device_get);
1102
1103/**
1104 * Release reference on device \a d.
1105 */
1106void lu_device_put(struct lu_device *d)
1107{
1108        LASSERT(atomic_read(&d->ld_ref) > 0);
1109        atomic_dec(&d->ld_ref);
1110}
1111EXPORT_SYMBOL(lu_device_put);
1112
1113/**
1114 * Initialize device \a d of type \a t.
1115 */
1116int lu_device_init(struct lu_device *d, struct lu_device_type *t)
1117{
1118        if (t->ldt_device_nr++ == 0 && t->ldt_ops->ldto_start != NULL)
1119                t->ldt_ops->ldto_start(t);
1120        memset(d, 0, sizeof(*d));
1121        atomic_set(&d->ld_ref, 0);
1122        d->ld_type = t;
1123        lu_ref_init(&d->ld_reference);
1124        INIT_LIST_HEAD(&d->ld_linkage);
1125        return 0;
1126}
1127EXPORT_SYMBOL(lu_device_init);
1128
1129/**
1130 * Finalize device \a d.
1131 */
1132void lu_device_fini(struct lu_device *d)
1133{
1134        struct lu_device_type *t;
1135
1136        t = d->ld_type;
1137        if (d->ld_obd != NULL) {
1138                d->ld_obd->obd_lu_dev = NULL;
1139                d->ld_obd = NULL;
1140        }
1141
1142        lu_ref_fini(&d->ld_reference);
1143        LASSERTF(atomic_read(&d->ld_ref) == 0,
1144                 "Refcount is %u\n", atomic_read(&d->ld_ref));
1145        LASSERT(t->ldt_device_nr > 0);
1146        if (--t->ldt_device_nr == 0 && t->ldt_ops->ldto_stop != NULL)
1147                t->ldt_ops->ldto_stop(t);
1148}
1149EXPORT_SYMBOL(lu_device_fini);
1150
1151/**
1152 * Initialize object \a o that is part of compound object \a h and was created
1153 * by device \a d.
1154 */
1155int lu_object_init(struct lu_object *o, struct lu_object_header *h,
1156                   struct lu_device *d)
1157{
1158        memset(o, 0, sizeof(*o));
1159        o->lo_header = h;
1160        o->lo_dev = d;
1161        lu_device_get(d);
1162        lu_ref_add_at(&d->ld_reference, &o->lo_dev_ref, "lu_object", o);
1163        INIT_LIST_HEAD(&o->lo_linkage);
1164
1165        return 0;
1166}
1167EXPORT_SYMBOL(lu_object_init);
1168
1169/**
1170 * Finalize object and release its resources.
1171 */
1172void lu_object_fini(struct lu_object *o)
1173{
1174        struct lu_device *dev = o->lo_dev;
1175
1176        LASSERT(list_empty(&o->lo_linkage));
1177
1178        if (dev != NULL) {
1179                lu_ref_del_at(&dev->ld_reference, &o->lo_dev_ref,
1180                              "lu_object", o);
1181                lu_device_put(dev);
1182                o->lo_dev = NULL;
1183        }
1184}
1185EXPORT_SYMBOL(lu_object_fini);
1186
1187/**
1188 * Add object \a o as first layer of compound object \a h
1189 *
1190 * This is typically called by the ->ldo_object_alloc() method of top-level
1191 * device.
1192 */
1193void lu_object_add_top(struct lu_object_header *h, struct lu_object *o)
1194{
1195        list_move(&o->lo_linkage, &h->loh_layers);
1196}
1197EXPORT_SYMBOL(lu_object_add_top);
1198
1199/**
1200 * Add object \a o as a layer of compound object, going after \a before.
1201 *
1202 * This is typically called by the ->ldo_object_alloc() method of \a
1203 * before->lo_dev.
1204 */
1205void lu_object_add(struct lu_object *before, struct lu_object *o)
1206{
1207        list_move(&o->lo_linkage, &before->lo_linkage);
1208}
1209EXPORT_SYMBOL(lu_object_add);
1210
1211/**
1212 * Initialize compound object.
1213 */
1214int lu_object_header_init(struct lu_object_header *h)
1215{
1216        memset(h, 0, sizeof(*h));
1217        atomic_set(&h->loh_ref, 1);
1218        INIT_HLIST_NODE(&h->loh_hash);
1219        INIT_LIST_HEAD(&h->loh_lru);
1220        INIT_LIST_HEAD(&h->loh_layers);
1221        lu_ref_init(&h->loh_reference);
1222        return 0;
1223}
1224EXPORT_SYMBOL(lu_object_header_init);
1225
1226/**
1227 * Finalize compound object.
1228 */
1229void lu_object_header_fini(struct lu_object_header *h)
1230{
1231        LASSERT(list_empty(&h->loh_layers));
1232        LASSERT(list_empty(&h->loh_lru));
1233        LASSERT(hlist_unhashed(&h->loh_hash));
1234        lu_ref_fini(&h->loh_reference);
1235}
1236EXPORT_SYMBOL(lu_object_header_fini);
1237
1238/**
1239 * Given a compound object, find its slice, corresponding to the device type
1240 * \a dtype.
1241 */
1242struct lu_object *lu_object_locate(struct lu_object_header *h,
1243                                   const struct lu_device_type *dtype)
1244{
1245        struct lu_object *o;
1246
1247        list_for_each_entry(o, &h->loh_layers, lo_linkage) {
1248                if (o->lo_dev->ld_type == dtype)
1249                        return o;
1250        }
1251        return NULL;
1252}
1253EXPORT_SYMBOL(lu_object_locate);
1254
1255
1256
1257/**
1258 * Finalize and free devices in the device stack.
1259 *
1260 * Finalize device stack by purging object cache, and calling
1261 * lu_device_type_operations::ldto_device_fini() and
1262 * lu_device_type_operations::ldto_device_free() on all devices in the stack.
1263 */
1264void lu_stack_fini(const struct lu_env *env, struct lu_device *top)
1265{
1266        struct lu_site   *site = top->ld_site;
1267        struct lu_device *scan;
1268        struct lu_device *next;
1269
1270        lu_site_purge(env, site, ~0);
1271        for (scan = top; scan != NULL; scan = next) {
1272                next = scan->ld_type->ldt_ops->ldto_device_fini(env, scan);
1273                lu_ref_del(&scan->ld_reference, "lu-stack", &lu_site_init);
1274                lu_device_put(scan);
1275        }
1276
1277        /* purge again. */
1278        lu_site_purge(env, site, ~0);
1279
1280        for (scan = top; scan != NULL; scan = next) {
1281                const struct lu_device_type *ldt = scan->ld_type;
1282                struct obd_type      *type;
1283
1284                next = ldt->ldt_ops->ldto_device_free(env, scan);
1285                type = ldt->ldt_obd_type;
1286                if (type != NULL) {
1287                        type->typ_refcnt--;
1288                        class_put_type(type);
1289                }
1290        }
1291}
1292EXPORT_SYMBOL(lu_stack_fini);
1293
1294enum {
1295        /**
1296         * Maximal number of tld slots.
1297         */
1298        LU_CONTEXT_KEY_NR = 40
1299};
1300
1301static struct lu_context_key *lu_keys[LU_CONTEXT_KEY_NR] = { NULL, };
1302
1303static DEFINE_SPINLOCK(lu_keys_guard);
1304
1305/**
1306 * Global counter incremented whenever key is registered, unregistered,
1307 * revived or quiesced. This is used to void unnecessary calls to
1308 * lu_context_refill(). No locking is provided, as initialization and shutdown
1309 * are supposed to be externally serialized.
1310 */
1311static unsigned key_set_version;
1312
1313/**
1314 * Register new key.
1315 */
1316int lu_context_key_register(struct lu_context_key *key)
1317{
1318        int result;
1319        int i;
1320
1321        LASSERT(key->lct_init != NULL);
1322        LASSERT(key->lct_fini != NULL);
1323        LASSERT(key->lct_tags != 0);
1324
1325        result = -ENFILE;
1326        spin_lock(&lu_keys_guard);
1327        for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1328                if (lu_keys[i] == NULL) {
1329                        key->lct_index = i;
1330                        atomic_set(&key->lct_used, 1);
1331                        lu_keys[i] = key;
1332                        lu_ref_init(&key->lct_reference);
1333                        result = 0;
1334                        ++key_set_version;
1335                        break;
1336                }
1337        }
1338        spin_unlock(&lu_keys_guard);
1339        return result;
1340}
1341EXPORT_SYMBOL(lu_context_key_register);
1342
1343static void key_fini(struct lu_context *ctx, int index)
1344{
1345        if (ctx->lc_value != NULL && ctx->lc_value[index] != NULL) {
1346                struct lu_context_key *key;
1347
1348                key = lu_keys[index];
1349                LASSERT(key != NULL);
1350                LASSERT(key->lct_fini != NULL);
1351                LASSERT(atomic_read(&key->lct_used) > 1);
1352
1353                key->lct_fini(ctx, key, ctx->lc_value[index]);
1354                lu_ref_del(&key->lct_reference, "ctx", ctx);
1355                atomic_dec(&key->lct_used);
1356
1357                if ((ctx->lc_tags & LCT_NOREF) == 0) {
1358#ifdef CONFIG_MODULE_UNLOAD
1359                        LINVRNT(module_refcount(key->lct_owner) > 0);
1360#endif
1361                        module_put(key->lct_owner);
1362                }
1363                ctx->lc_value[index] = NULL;
1364        }
1365}
1366
1367/**
1368 * Deregister key.
1369 */
1370void lu_context_key_degister(struct lu_context_key *key)
1371{
1372        LASSERT(atomic_read(&key->lct_used) >= 1);
1373        LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1374
1375        lu_context_key_quiesce(key);
1376
1377        ++key_set_version;
1378        spin_lock(&lu_keys_guard);
1379        key_fini(&lu_shrink_env.le_ctx, key->lct_index);
1380        if (lu_keys[key->lct_index]) {
1381                lu_keys[key->lct_index] = NULL;
1382                lu_ref_fini(&key->lct_reference);
1383        }
1384        spin_unlock(&lu_keys_guard);
1385
1386        LASSERTF(atomic_read(&key->lct_used) == 1,
1387                 "key has instances: %d\n",
1388                 atomic_read(&key->lct_used));
1389}
1390EXPORT_SYMBOL(lu_context_key_degister);
1391
1392/**
1393 * Register a number of keys. This has to be called after all keys have been
1394 * initialized by a call to LU_CONTEXT_KEY_INIT().
1395 */
1396int lu_context_key_register_many(struct lu_context_key *k, ...)
1397{
1398        struct lu_context_key *key = k;
1399        va_list args;
1400        int result;
1401
1402        va_start(args, k);
1403        do {
1404                result = lu_context_key_register(key);
1405                if (result)
1406                        break;
1407                key = va_arg(args, struct lu_context_key *);
1408        } while (key != NULL);
1409        va_end(args);
1410
1411        if (result != 0) {
1412                va_start(args, k);
1413                while (k != key) {
1414                        lu_context_key_degister(k);
1415                        k = va_arg(args, struct lu_context_key *);
1416                }
1417                va_end(args);
1418        }
1419
1420        return result;
1421}
1422EXPORT_SYMBOL(lu_context_key_register_many);
1423
1424/**
1425 * De-register a number of keys. This is a dual to
1426 * lu_context_key_register_many().
1427 */
1428void lu_context_key_degister_many(struct lu_context_key *k, ...)
1429{
1430        va_list args;
1431
1432        va_start(args, k);
1433        do {
1434                lu_context_key_degister(k);
1435                k = va_arg(args, struct lu_context_key*);
1436        } while (k != NULL);
1437        va_end(args);
1438}
1439EXPORT_SYMBOL(lu_context_key_degister_many);
1440
1441/**
1442 * Revive a number of keys.
1443 */
1444void lu_context_key_revive_many(struct lu_context_key *k, ...)
1445{
1446        va_list args;
1447
1448        va_start(args, k);
1449        do {
1450                lu_context_key_revive(k);
1451                k = va_arg(args, struct lu_context_key*);
1452        } while (k != NULL);
1453        va_end(args);
1454}
1455EXPORT_SYMBOL(lu_context_key_revive_many);
1456
1457/**
1458 * Quiescent a number of keys.
1459 */
1460void lu_context_key_quiesce_many(struct lu_context_key *k, ...)
1461{
1462        va_list args;
1463
1464        va_start(args, k);
1465        do {
1466                lu_context_key_quiesce(k);
1467                k = va_arg(args, struct lu_context_key*);
1468        } while (k != NULL);
1469        va_end(args);
1470}
1471EXPORT_SYMBOL(lu_context_key_quiesce_many);
1472
1473/**
1474 * Return value associated with key \a key in context \a ctx.
1475 */
1476void *lu_context_key_get(const struct lu_context *ctx,
1477                         const struct lu_context_key *key)
1478{
1479        LINVRNT(ctx->lc_state == LCS_ENTERED);
1480        LINVRNT(0 <= key->lct_index && key->lct_index < ARRAY_SIZE(lu_keys));
1481        LASSERT(lu_keys[key->lct_index] == key);
1482        return ctx->lc_value[key->lct_index];
1483}
1484EXPORT_SYMBOL(lu_context_key_get);
1485
1486/**
1487 * List of remembered contexts. XXX document me.
1488 */
1489static LIST_HEAD(lu_context_remembered);
1490
1491/**
1492 * Destroy \a key in all remembered contexts. This is used to destroy key
1493 * values in "shared" contexts (like service threads), when a module owning
1494 * the key is about to be unloaded.
1495 */
1496void lu_context_key_quiesce(struct lu_context_key *key)
1497{
1498        struct lu_context *ctx;
1499
1500        if (!(key->lct_tags & LCT_QUIESCENT)) {
1501                /*
1502                 * XXX layering violation.
1503                 */
1504                key->lct_tags |= LCT_QUIESCENT;
1505                /*
1506                 * XXX memory barrier has to go here.
1507                 */
1508                spin_lock(&lu_keys_guard);
1509                list_for_each_entry(ctx, &lu_context_remembered,
1510                                        lc_remember)
1511                        key_fini(ctx, key->lct_index);
1512                spin_unlock(&lu_keys_guard);
1513                ++key_set_version;
1514        }
1515}
1516EXPORT_SYMBOL(lu_context_key_quiesce);
1517
1518void lu_context_key_revive(struct lu_context_key *key)
1519{
1520        key->lct_tags &= ~LCT_QUIESCENT;
1521        ++key_set_version;
1522}
1523EXPORT_SYMBOL(lu_context_key_revive);
1524
1525static void keys_fini(struct lu_context *ctx)
1526{
1527        int     i;
1528
1529        if (ctx->lc_value == NULL)
1530                return;
1531
1532        for (i = 0; i < ARRAY_SIZE(lu_keys); ++i)
1533                key_fini(ctx, i);
1534
1535        OBD_FREE(ctx->lc_value, ARRAY_SIZE(lu_keys) * sizeof(ctx->lc_value[0]));
1536        ctx->lc_value = NULL;
1537}
1538
1539static int keys_fill(struct lu_context *ctx)
1540{
1541        int i;
1542
1543        LINVRNT(ctx->lc_value != NULL);
1544        for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1545                struct lu_context_key *key;
1546
1547                key = lu_keys[i];
1548                if (ctx->lc_value[i] == NULL && key != NULL &&
1549                    (key->lct_tags & ctx->lc_tags) &&
1550                    /*
1551                     * Don't create values for a LCT_QUIESCENT key, as this
1552                     * will pin module owning a key.
1553                     */
1554                    !(key->lct_tags & LCT_QUIESCENT)) {
1555                        void *value;
1556
1557                        LINVRNT(key->lct_init != NULL);
1558                        LINVRNT(key->lct_index == i);
1559
1560                        value = key->lct_init(ctx, key);
1561                        if (unlikely(IS_ERR(value)))
1562                                return PTR_ERR(value);
1563
1564                        if (!(ctx->lc_tags & LCT_NOREF))
1565                                try_module_get(key->lct_owner);
1566                        lu_ref_add_atomic(&key->lct_reference, "ctx", ctx);
1567                        atomic_inc(&key->lct_used);
1568                        /*
1569                         * This is the only place in the code, where an
1570                         * element of ctx->lc_value[] array is set to non-NULL
1571                         * value.
1572                         */
1573                        ctx->lc_value[i] = value;
1574                        if (key->lct_exit != NULL)
1575                                ctx->lc_tags |= LCT_HAS_EXIT;
1576                }
1577                ctx->lc_version = key_set_version;
1578        }
1579        return 0;
1580}
1581
1582static int keys_init(struct lu_context *ctx)
1583{
1584        OBD_ALLOC(ctx->lc_value,
1585                  ARRAY_SIZE(lu_keys) * sizeof(ctx->lc_value[0]));
1586        if (likely(ctx->lc_value != NULL))
1587                return keys_fill(ctx);
1588
1589        return -ENOMEM;
1590}
1591
1592/**
1593 * Initialize context data-structure. Create values for all keys.
1594 */
1595int lu_context_init(struct lu_context *ctx, __u32 tags)
1596{
1597        int     rc;
1598
1599        memset(ctx, 0, sizeof(*ctx));
1600        ctx->lc_state = LCS_INITIALIZED;
1601        ctx->lc_tags = tags;
1602        if (tags & LCT_REMEMBER) {
1603                spin_lock(&lu_keys_guard);
1604                list_add(&ctx->lc_remember, &lu_context_remembered);
1605                spin_unlock(&lu_keys_guard);
1606        } else {
1607                INIT_LIST_HEAD(&ctx->lc_remember);
1608        }
1609
1610        rc = keys_init(ctx);
1611        if (rc != 0)
1612                lu_context_fini(ctx);
1613
1614        return rc;
1615}
1616EXPORT_SYMBOL(lu_context_init);
1617
1618/**
1619 * Finalize context data-structure. Destroy key values.
1620 */
1621void lu_context_fini(struct lu_context *ctx)
1622{
1623        LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1624        ctx->lc_state = LCS_FINALIZED;
1625
1626        if ((ctx->lc_tags & LCT_REMEMBER) == 0) {
1627                LASSERT(list_empty(&ctx->lc_remember));
1628                keys_fini(ctx);
1629
1630        } else { /* could race with key degister */
1631                spin_lock(&lu_keys_guard);
1632                keys_fini(ctx);
1633                list_del_init(&ctx->lc_remember);
1634                spin_unlock(&lu_keys_guard);
1635        }
1636}
1637EXPORT_SYMBOL(lu_context_fini);
1638
1639/**
1640 * Called before entering context.
1641 */
1642void lu_context_enter(struct lu_context *ctx)
1643{
1644        LINVRNT(ctx->lc_state == LCS_INITIALIZED || ctx->lc_state == LCS_LEFT);
1645        ctx->lc_state = LCS_ENTERED;
1646}
1647EXPORT_SYMBOL(lu_context_enter);
1648
1649/**
1650 * Called after exiting from \a ctx
1651 */
1652void lu_context_exit(struct lu_context *ctx)
1653{
1654        int i;
1655
1656        LINVRNT(ctx->lc_state == LCS_ENTERED);
1657        ctx->lc_state = LCS_LEFT;
1658        if (ctx->lc_tags & LCT_HAS_EXIT && ctx->lc_value != NULL) {
1659                for (i = 0; i < ARRAY_SIZE(lu_keys); ++i) {
1660                        if (ctx->lc_value[i] != NULL) {
1661                                struct lu_context_key *key;
1662
1663                                key = lu_keys[i];
1664                                LASSERT(key != NULL);
1665                                if (key->lct_exit != NULL)
1666                                        key->lct_exit(ctx,
1667                                                      key, ctx->lc_value[i]);
1668                        }
1669                }
1670        }
1671}
1672EXPORT_SYMBOL(lu_context_exit);
1673
1674/**
1675 * Allocate for context all missing keys that were registered after context
1676 * creation. key_set_version is only changed in rare cases when modules
1677 * are loaded and removed.
1678 */
1679int lu_context_refill(struct lu_context *ctx)
1680{
1681        return likely(ctx->lc_version == key_set_version) ? 0 : keys_fill(ctx);
1682}
1683EXPORT_SYMBOL(lu_context_refill);
1684
1685/**
1686 * lu_ctx_tags/lu_ses_tags will be updated if there are new types of
1687 * obd being added. Currently, this is only used on client side, specifically
1688 * for echo device client, for other stack (like ptlrpc threads), context are
1689 * predefined when the lu_device type are registered, during the module probe
1690 * phase.
1691 */
1692__u32 lu_context_tags_default = 0;
1693__u32 lu_session_tags_default = 0;
1694
1695void lu_context_tags_update(__u32 tags)
1696{
1697        spin_lock(&lu_keys_guard);
1698        lu_context_tags_default |= tags;
1699        key_set_version++;
1700        spin_unlock(&lu_keys_guard);
1701}
1702EXPORT_SYMBOL(lu_context_tags_update);
1703
1704void lu_context_tags_clear(__u32 tags)
1705{
1706        spin_lock(&lu_keys_guard);
1707        lu_context_tags_default &= ~tags;
1708        key_set_version++;
1709        spin_unlock(&lu_keys_guard);
1710}
1711EXPORT_SYMBOL(lu_context_tags_clear);
1712
1713void lu_session_tags_update(__u32 tags)
1714{
1715        spin_lock(&lu_keys_guard);
1716        lu_session_tags_default |= tags;
1717        key_set_version++;
1718        spin_unlock(&lu_keys_guard);
1719}
1720EXPORT_SYMBOL(lu_session_tags_update);
1721
1722void lu_session_tags_clear(__u32 tags)
1723{
1724        spin_lock(&lu_keys_guard);
1725        lu_session_tags_default &= ~tags;
1726        key_set_version++;
1727        spin_unlock(&lu_keys_guard);
1728}
1729EXPORT_SYMBOL(lu_session_tags_clear);
1730
1731int lu_env_init(struct lu_env *env, __u32 tags)
1732{
1733        int result;
1734
1735        env->le_ses = NULL;
1736        result = lu_context_init(&env->le_ctx, tags);
1737        if (likely(result == 0))
1738                lu_context_enter(&env->le_ctx);
1739        return result;
1740}
1741EXPORT_SYMBOL(lu_env_init);
1742
1743void lu_env_fini(struct lu_env *env)
1744{
1745        lu_context_exit(&env->le_ctx);
1746        lu_context_fini(&env->le_ctx);
1747        env->le_ses = NULL;
1748}
1749EXPORT_SYMBOL(lu_env_fini);
1750
1751int lu_env_refill(struct lu_env *env)
1752{
1753        int result;
1754
1755        result = lu_context_refill(&env->le_ctx);
1756        if (result == 0 && env->le_ses != NULL)
1757                result = lu_context_refill(env->le_ses);
1758        return result;
1759}
1760EXPORT_SYMBOL(lu_env_refill);
1761
1762/**
1763 * Currently, this API will only be used by echo client.
1764 * Because echo client and normal lustre client will share
1765 * same cl_env cache. So echo client needs to refresh
1766 * the env context after it get one from the cache, especially
1767 * when normal client and echo client co-exist in the same client.
1768 */
1769int lu_env_refill_by_tags(struct lu_env *env, __u32 ctags,
1770                          __u32 stags)
1771{
1772        if ((env->le_ctx.lc_tags & ctags) != ctags) {
1773                env->le_ctx.lc_version = 0;
1774                env->le_ctx.lc_tags |= ctags;
1775        }
1776
1777        if (env->le_ses && (env->le_ses->lc_tags & stags) != stags) {
1778                env->le_ses->lc_version = 0;
1779                env->le_ses->lc_tags |= stags;
1780        }
1781
1782        return lu_env_refill(env);
1783}
1784EXPORT_SYMBOL(lu_env_refill_by_tags);
1785
1786
1787typedef struct lu_site_stats{
1788        unsigned        lss_populated;
1789        unsigned        lss_max_search;
1790        unsigned        lss_total;
1791        unsigned        lss_busy;
1792} lu_site_stats_t;
1793
1794static void lu_site_stats_get(struct cfs_hash *hs,
1795                              lu_site_stats_t *stats, int populated)
1796{
1797        struct cfs_hash_bd bd;
1798        int        i;
1799
1800        cfs_hash_for_each_bucket(hs, &bd, i) {
1801                struct lu_site_bkt_data *bkt = cfs_hash_bd_extra_get(hs, &bd);
1802                struct hlist_head       *hhead;
1803
1804                cfs_hash_bd_lock(hs, &bd, 1);
1805                stats->lss_busy  += bkt->lsb_busy;
1806                stats->lss_total += cfs_hash_bd_count_get(&bd);
1807                stats->lss_max_search = max((int)stats->lss_max_search,
1808                                            cfs_hash_bd_depmax_get(&bd));
1809                if (!populated) {
1810                        cfs_hash_bd_unlock(hs, &bd, 1);
1811                        continue;
1812                }
1813
1814                cfs_hash_bd_for_each_hlist(hs, &bd, hhead) {
1815                        if (!hlist_empty(hhead))
1816                                stats->lss_populated++;
1817                }
1818                cfs_hash_bd_unlock(hs, &bd, 1);
1819        }
1820}
1821
1822
1823/*
1824 * There exists a potential lock inversion deadlock scenario when using
1825 * Lustre on top of ZFS. This occurs between one of ZFS's
1826 * buf_hash_table.ht_lock's, and Lustre's lu_sites_guard lock. Essentially,
1827 * thread A will take the lu_sites_guard lock and sleep on the ht_lock,
1828 * while thread B will take the ht_lock and sleep on the lu_sites_guard
1829 * lock. Obviously neither thread will wake and drop their respective hold
1830 * on their lock.
1831 *
1832 * To prevent this from happening we must ensure the lu_sites_guard lock is
1833 * not taken while down this code path. ZFS reliably does not set the
1834 * __GFP_FS bit in its code paths, so this can be used to determine if it
1835 * is safe to take the lu_sites_guard lock.
1836 *
1837 * Ideally we should accurately return the remaining number of cached
1838 * objects without taking the  lu_sites_guard lock, but this is not
1839 * possible in the current implementation.
1840 */
1841static unsigned long lu_cache_shrink_count(struct shrinker *sk,
1842                                           struct shrink_control *sc)
1843{
1844        lu_site_stats_t stats;
1845        struct lu_site *s;
1846        struct lu_site *tmp;
1847        unsigned long cached = 0;
1848
1849        if (!(sc->gfp_mask & __GFP_FS))
1850                return 0;
1851
1852        mutex_lock(&lu_sites_guard);
1853        list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
1854                memset(&stats, 0, sizeof(stats));
1855                lu_site_stats_get(s->ls_obj_hash, &stats, 0);
1856                cached += stats.lss_total - stats.lss_busy;
1857        }
1858        mutex_unlock(&lu_sites_guard);
1859
1860        cached = (cached / 100) * sysctl_vfs_cache_pressure;
1861        CDEBUG(D_INODE, "%ld objects cached\n", cached);
1862        return cached;
1863}
1864
1865static unsigned long lu_cache_shrink_scan(struct shrinker *sk,
1866                                          struct shrink_control *sc)
1867{
1868        struct lu_site *s;
1869        struct lu_site *tmp;
1870        unsigned long remain = sc->nr_to_scan, freed = 0;
1871        LIST_HEAD(splice);
1872
1873        if (!(sc->gfp_mask & __GFP_FS))
1874                /* We must not take the lu_sites_guard lock when
1875                 * __GFP_FS is *not* set because of the deadlock
1876                 * possibility detailed above. Additionally,
1877                 * since we cannot determine the number of
1878                 * objects in the cache without taking this
1879                 * lock, we're in a particularly tough spot. As
1880                 * a result, we'll just lie and say our cache is
1881                 * empty. This _should_ be ok, as we can't
1882                 * reclaim objects when __GFP_FS is *not* set
1883                 * anyways.
1884                 */
1885                return SHRINK_STOP;
1886
1887        mutex_lock(&lu_sites_guard);
1888        list_for_each_entry_safe(s, tmp, &lu_sites, ls_linkage) {
1889                freed = lu_site_purge(&lu_shrink_env, s, remain);
1890                remain -= freed;
1891                /*
1892                 * Move just shrunk site to the tail of site list to
1893                 * assure shrinking fairness.
1894                 */
1895                list_move_tail(&s->ls_linkage, &splice);
1896        }
1897        list_splice(&splice, lu_sites.prev);
1898        mutex_unlock(&lu_sites_guard);
1899
1900        return sc->nr_to_scan - remain;
1901}
1902
1903/*
1904 * Debugging stuff.
1905 */
1906
1907/**
1908 * Environment to be used in debugger, contains all tags.
1909 */
1910struct lu_env lu_debugging_env;
1911
1912/**
1913 * Debugging printer function using printk().
1914 */
1915int lu_printk_printer(const struct lu_env *env,
1916                      void *unused, const char *format, ...)
1917{
1918        va_list args;
1919
1920        va_start(args, format);
1921        vprintk(format, args);
1922        va_end(args);
1923        return 0;
1924}
1925
1926static struct shrinker lu_site_shrinker = {
1927        .count_objects  = lu_cache_shrink_count,
1928        .scan_objects   = lu_cache_shrink_scan,
1929        .seeks          = DEFAULT_SEEKS,
1930};
1931
1932/**
1933 * Initialization of global lu_* data.
1934 */
1935int lu_global_init(void)
1936{
1937        int result;
1938
1939        CDEBUG(D_INFO, "Lustre LU module (%p).\n", &lu_keys);
1940
1941        result = lu_ref_global_init();
1942        if (result != 0)
1943                return result;
1944
1945        LU_CONTEXT_KEY_INIT(&lu_global_key);
1946        result = lu_context_key_register(&lu_global_key);
1947        if (result != 0)
1948                return result;
1949
1950        /*
1951         * At this level, we don't know what tags are needed, so allocate them
1952         * conservatively. This should not be too bad, because this
1953         * environment is global.
1954         */
1955        mutex_lock(&lu_sites_guard);
1956        result = lu_env_init(&lu_shrink_env, LCT_SHRINKER);
1957        mutex_unlock(&lu_sites_guard);
1958        if (result != 0)
1959                return result;
1960
1961        /*
1962         * seeks estimation: 3 seeks to read a record from oi, one to read
1963         * inode, one for ea. Unfortunately setting this high value results in
1964         * lu_object/inode cache consuming all the memory.
1965         */
1966        register_shrinker(&lu_site_shrinker);
1967
1968        return result;
1969}
1970
1971/**
1972 * Dual to lu_global_init().
1973 */
1974void lu_global_fini(void)
1975{
1976        unregister_shrinker(&lu_site_shrinker);
1977        lu_context_key_degister(&lu_global_key);
1978
1979        /*
1980         * Tear shrinker environment down _after_ de-registering
1981         * lu_global_key, because the latter has a value in the former.
1982         */
1983        mutex_lock(&lu_sites_guard);
1984        lu_env_fini(&lu_shrink_env);
1985        mutex_unlock(&lu_sites_guard);
1986
1987        lu_ref_global_fini();
1988}
1989
1990static __u32 ls_stats_read(struct lprocfs_stats *stats, int idx)
1991{
1992#if defined (CONFIG_PROC_FS)
1993        struct lprocfs_counter ret;
1994
1995        lprocfs_stats_collect(stats, idx, &ret);
1996        return (__u32)ret.lc_count;
1997#else
1998        return 0;
1999#endif
2000}
2001
2002/**
2003 * Output site statistical counters into a buffer. Suitable for
2004 * lprocfs_rd_*()-style functions.
2005 */
2006int lu_site_stats_print(const struct lu_site *s, struct seq_file *m)
2007{
2008        lu_site_stats_t stats;
2009
2010        memset(&stats, 0, sizeof(stats));
2011        lu_site_stats_get(s->ls_obj_hash, &stats, 1);
2012
2013        seq_printf(m, "%d/%d %d/%d %d %d %d %d %d %d %d\n",
2014                   stats.lss_busy,
2015                   stats.lss_total,
2016                   stats.lss_populated,
2017                   CFS_HASH_NHLIST(s->ls_obj_hash),
2018                   stats.lss_max_search,
2019                   ls_stats_read(s->ls_stats, LU_SS_CREATED),
2020                   ls_stats_read(s->ls_stats, LU_SS_CACHE_HIT),
2021                   ls_stats_read(s->ls_stats, LU_SS_CACHE_MISS),
2022                   ls_stats_read(s->ls_stats, LU_SS_CACHE_RACE),
2023                   ls_stats_read(s->ls_stats, LU_SS_CACHE_DEATH_RACE),
2024                   ls_stats_read(s->ls_stats, LU_SS_LRU_PURGED));
2025        return 0;
2026}
2027EXPORT_SYMBOL(lu_site_stats_print);
2028
2029/**
2030 * Helper function to initialize a number of kmem slab caches at once.
2031 */
2032int lu_kmem_init(struct lu_kmem_descr *caches)
2033{
2034        int result;
2035        struct lu_kmem_descr *iter = caches;
2036
2037        for (result = 0; iter->ckd_cache != NULL; ++iter) {
2038                *iter->ckd_cache = kmem_cache_create(iter->ckd_name,
2039                                                        iter->ckd_size,
2040                                                        0, 0, NULL);
2041                if (*iter->ckd_cache == NULL) {
2042                        result = -ENOMEM;
2043                        /* free all previously allocated caches */
2044                        lu_kmem_fini(caches);
2045                        break;
2046                }
2047        }
2048        return result;
2049}
2050EXPORT_SYMBOL(lu_kmem_init);
2051
2052/**
2053 * Helper function to finalize a number of kmem slab cached at once. Dual to
2054 * lu_kmem_init().
2055 */
2056void lu_kmem_fini(struct lu_kmem_descr *caches)
2057{
2058        for (; caches->ckd_cache != NULL; ++caches) {
2059                if (*caches->ckd_cache != NULL) {
2060                        kmem_cache_destroy(*caches->ckd_cache);
2061                        *caches->ckd_cache = NULL;
2062                }
2063        }
2064}
2065EXPORT_SYMBOL(lu_kmem_fini);
2066
2067/**
2068 * Temporary solution to be able to assign fid in ->do_create()
2069 * till we have fully-functional OST fids
2070 */
2071void lu_object_assign_fid(const struct lu_env *env, struct lu_object *o,
2072                          const struct lu_fid *fid)
2073{
2074        struct lu_site          *s = o->lo_dev->ld_site;
2075        struct lu_fid           *old = &o->lo_header->loh_fid;
2076        struct lu_site_bkt_data *bkt;
2077        struct lu_object        *shadow;
2078        wait_queue_t             waiter;
2079        struct cfs_hash         *hs;
2080        struct cfs_hash_bd       bd;
2081        __u64                    version = 0;
2082
2083        LASSERT(fid_is_zero(old));
2084
2085        hs = s->ls_obj_hash;
2086        cfs_hash_bd_get_and_lock(hs, (void *)fid, &bd, 1);
2087        shadow = htable_lookup(s, &bd, fid, &waiter, &version);
2088        /* supposed to be unique */
2089        LASSERT(IS_ERR(shadow) && PTR_ERR(shadow) == -ENOENT);
2090        *old = *fid;
2091        bkt = cfs_hash_bd_extra_get(hs, &bd);
2092        cfs_hash_bd_add_locked(hs, &bd, &o->lo_header->loh_hash);
2093        bkt->lsb_busy++;
2094        cfs_hash_bd_unlock(hs, &bd, 1);
2095}
2096EXPORT_SYMBOL(lu_object_assign_fid);
2097
2098/**
2099 * allocates object with 0 (non-assigned) fid
2100 * XXX: temporary solution to be able to assign fid in ->do_create()
2101 *      till we have fully-functional OST fids
2102 */
2103struct lu_object *lu_object_anon(const struct lu_env *env,
2104                                 struct lu_device *dev,
2105                                 const struct lu_object_conf *conf)
2106{
2107        struct lu_fid     fid;
2108        struct lu_object *o;
2109
2110        fid_zero(&fid);
2111        o = lu_object_alloc(env, dev, &fid, conf);
2112
2113        return o;
2114}
2115EXPORT_SYMBOL(lu_object_anon);
2116
2117struct lu_buf LU_BUF_NULL = {
2118        .lb_buf = NULL,
2119        .lb_len = 0
2120};
2121EXPORT_SYMBOL(LU_BUF_NULL);
2122
2123void lu_buf_free(struct lu_buf *buf)
2124{
2125        LASSERT(buf);
2126        if (buf->lb_buf) {
2127                LASSERT(buf->lb_len > 0);
2128                OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2129                buf->lb_buf = NULL;
2130                buf->lb_len = 0;
2131        }
2132}
2133EXPORT_SYMBOL(lu_buf_free);
2134
2135void lu_buf_alloc(struct lu_buf *buf, int size)
2136{
2137        LASSERT(buf);
2138        LASSERT(buf->lb_buf == NULL);
2139        LASSERT(buf->lb_len == 0);
2140        OBD_ALLOC_LARGE(buf->lb_buf, size);
2141        if (likely(buf->lb_buf))
2142                buf->lb_len = size;
2143}
2144EXPORT_SYMBOL(lu_buf_alloc);
2145
2146void lu_buf_realloc(struct lu_buf *buf, int size)
2147{
2148        lu_buf_free(buf);
2149        lu_buf_alloc(buf, size);
2150}
2151EXPORT_SYMBOL(lu_buf_realloc);
2152
2153struct lu_buf *lu_buf_check_and_alloc(struct lu_buf *buf, int len)
2154{
2155        if (buf->lb_buf == NULL && buf->lb_len == 0)
2156                lu_buf_alloc(buf, len);
2157
2158        if ((len > buf->lb_len) && (buf->lb_buf != NULL))
2159                lu_buf_realloc(buf, len);
2160
2161        return buf;
2162}
2163EXPORT_SYMBOL(lu_buf_check_and_alloc);
2164
2165/**
2166 * Increase the size of the \a buf.
2167 * preserves old data in buffer
2168 * old buffer remains unchanged on error
2169 * \retval 0 or -ENOMEM
2170 */
2171int lu_buf_check_and_grow(struct lu_buf *buf, int len)
2172{
2173        char *ptr;
2174
2175        if (len <= buf->lb_len)
2176                return 0;
2177
2178        OBD_ALLOC_LARGE(ptr, len);
2179        if (ptr == NULL)
2180                return -ENOMEM;
2181
2182        /* Free the old buf */
2183        if (buf->lb_buf != NULL) {
2184                memcpy(ptr, buf->lb_buf, buf->lb_len);
2185                OBD_FREE_LARGE(buf->lb_buf, buf->lb_len);
2186        }
2187
2188        buf->lb_buf = ptr;
2189        buf->lb_len = len;
2190        return 0;
2191}
2192EXPORT_SYMBOL(lu_buf_check_and_grow);
2193