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