Whamcloud - gitweb
LU-4423 mem: remove GFP_IOFS
[fs/lustre-release.git] / lustre / osd-ldiskfs / osd_handler.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/osd/osd_handler.c
37  *
38  * Top-level entry points into osd module
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
42  */
43
44 #define DEBUG_SUBSYSTEM S_OSD
45
46 #include <linux/module.h>
47 #include <linux/user_namespace.h>
48 #ifdef HAVE_UIDGID_HEADER
49 # include <linux/uidgid.h>
50 #endif
51
52 /* LUSTRE_VERSION_CODE */
53 #include <lustre_ver.h>
54 /* prerequisite for linux/xattr.h */
55 #include <linux/types.h>
56 /* prerequisite for linux/xattr.h */
57 #include <linux/fs.h>
58 /* XATTR_{REPLACE,CREATE} */
59 #include <linux/xattr.h>
60
61 #include <ldiskfs/ldiskfs.h>
62 #include <ldiskfs/xattr.h>
63 #include <ldiskfs/ldiskfs_extents.h>
64 #undef ENTRY
65 /*
66  * struct OBD_{ALLOC,FREE}*()
67  * OBD_FAIL_CHECK
68  */
69 #include <obd_support.h>
70 /* struct ptlrpc_thread */
71 #include <lustre_net.h>
72 #include <lustre_fid.h>
73 /* process_config */
74 #include <lustre_param.h>
75
76 #include "osd_internal.h"
77 #include "osd_dynlocks.h"
78
79 /* llo_* api support */
80 #include <md_object.h>
81 #include <lustre_quota.h>
82
83 #include <lustre_linkea.h>
84
85 int ldiskfs_pdo = 1;
86 module_param(ldiskfs_pdo, int, 0644);
87 MODULE_PARM_DESC(ldiskfs_pdo, "ldiskfs with parallel directory operations");
88
89 int ldiskfs_track_declares_assert;
90 module_param(ldiskfs_track_declares_assert, int, 0644);
91 MODULE_PARM_DESC(ldiskfs_track_declares_assert, "LBUG during tracking of declares");
92
93 /* Slab to allocate dynlocks */
94 struct kmem_cache *dynlock_cachep;
95
96 /* Slab to allocate osd_it_ea */
97 struct kmem_cache *osd_itea_cachep;
98
99 static struct lu_kmem_descr ldiskfs_caches[] = {
100         {
101                 .ckd_cache = &dynlock_cachep,
102                 .ckd_name  = "dynlock_cache",
103                 .ckd_size  = sizeof(struct dynlock_handle)
104         },
105         {
106                 .ckd_cache = &osd_itea_cachep,
107                 .ckd_name  = "osd_itea_cache",
108                 .ckd_size  = sizeof(struct osd_it_ea)
109         },
110         {
111                 .ckd_cache = NULL
112         }
113 };
114
115 static const char dot[] = ".";
116 static const char dotdot[] = "..";
117 static const char remote_obj_dir[] = "REM_OBJ_DIR";
118
119 static const struct lu_object_operations      osd_lu_obj_ops;
120 static const struct dt_object_operations      osd_obj_ops;
121 static const struct dt_object_operations      osd_obj_ea_ops;
122 static const struct dt_object_operations      osd_obj_otable_it_ops;
123 static const struct dt_index_operations       osd_index_iam_ops;
124 static const struct dt_index_operations       osd_index_ea_ops;
125
126 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
127                           const struct lu_fid *fid);
128 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
129                                                 struct osd_device *osd);
130
131 int osd_trans_declare_op2rb[] = {
132         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
133         [OSD_OT_PUNCH]          = OSD_OT_MAX,
134         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
135         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
136         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
137         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
138         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
139         [OSD_OT_WRITE]          = OSD_OT_WRITE,
140         [OSD_OT_INSERT]         = OSD_OT_DELETE,
141         [OSD_OT_DELETE]         = OSD_OT_INSERT,
142         [OSD_OT_QUOTA]          = OSD_OT_MAX,
143 };
144
145 static int osd_has_index(const struct osd_object *obj)
146 {
147         return obj->oo_dt.do_index_ops != NULL;
148 }
149
150 static int osd_object_invariant(const struct lu_object *l)
151 {
152         return osd_invariant(osd_obj(l));
153 }
154
155 /*
156  * Concurrency: doesn't matter
157  */
158
159 /*
160  * Concurrency: doesn't matter
161  */
162 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
163 {
164         struct osd_thread_info *oti = osd_oti_get(env);
165         return oti->oti_w_locks > 0 && o->oo_owner == env;
166 }
167
168 /*
169  * Concurrency: doesn't access mutable data
170  */
171 static int osd_root_get(const struct lu_env *env,
172                         struct dt_device *dev, struct lu_fid *f)
173 {
174         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
175         return 0;
176 }
177
178 /*
179  * the following set of functions are used to maintain per-thread
180  * cache of FID->ino mapping. this mechanism is needed to resolve
181  * FID to inode at dt_insert() which in turn stores ino in the
182  * directory entries to keep ldiskfs compatible with ext[34].
183  * due to locking-originated restrictions we can't lookup ino
184  * using LU cache (deadlock is possible). lookup using OI is quite
185  * expensive. so instead we maintain this cache and methods like
186  * dt_create() fill it. so in the majority of cases dt_insert() is
187  * able to find needed mapping in lockless manner.
188  */
189 static struct osd_idmap_cache *
190 osd_idc_find(const struct lu_env *env, struct osd_device *osd,
191              const struct lu_fid *fid)
192 {
193         struct osd_thread_info  *oti   = osd_oti_get(env);
194         struct osd_idmap_cache  *idc    = oti->oti_ins_cache;
195         int i;
196         for (i = 0; i < oti->oti_ins_cache_used; i++) {
197                 if (!lu_fid_eq(&idc[i].oic_fid, fid))
198                         continue;
199                 if (idc[i].oic_dev != osd)
200                         continue;
201
202                 return idc + i;
203         }
204
205         return NULL;
206 }
207
208 static struct osd_idmap_cache *
209 osd_idc_add(const struct lu_env *env, struct osd_device *osd,
210             const struct lu_fid *fid)
211 {
212         struct osd_thread_info  *oti   = osd_oti_get(env);
213         struct osd_idmap_cache  *idc;
214         int i;
215
216         if (unlikely(oti->oti_ins_cache_used >= oti->oti_ins_cache_size)) {
217                 i = oti->oti_ins_cache_size * 2;
218                 if (i == 0)
219                         i = OSD_INS_CACHE_SIZE;
220                 OBD_ALLOC(idc, sizeof(*idc) * i);
221                 if (idc == NULL)
222                         return ERR_PTR(-ENOMEM);
223                 if (oti->oti_ins_cache != NULL) {
224                         memcpy(idc, oti->oti_ins_cache,
225                                oti->oti_ins_cache_used * sizeof(*idc));
226                         OBD_FREE(oti->oti_ins_cache,
227                                  oti->oti_ins_cache_used * sizeof(*idc));
228                 }
229                 oti->oti_ins_cache = idc;
230                 oti->oti_ins_cache_size = i;
231         }
232
233         idc = oti->oti_ins_cache + oti->oti_ins_cache_used++;
234         idc->oic_fid = *fid;
235         idc->oic_dev = osd;
236         idc->oic_lid.oii_ino = 0;
237         idc->oic_lid.oii_gen = 0;
238         idc->oic_remote = 0;
239
240         return idc;
241 }
242
243 /*
244  * lookup mapping for the given fid in the cache, initialize a
245  * new one if not found. the initialization checks whether the
246  * object is local or remote. for local objects, OI is used to
247  * learn ino/generation. the function is used when the caller
248  * has no information about the object, e.g. at dt_insert().
249  */
250 static struct osd_idmap_cache *
251 osd_idc_find_or_init(const struct lu_env *env, struct osd_device *osd,
252                      const struct lu_fid *fid)
253 {
254         struct osd_idmap_cache *idc;
255         int rc;
256
257         idc = osd_idc_find(env, osd, fid);
258         LASSERT(!IS_ERR(idc));
259         if (idc != NULL)
260                 return idc;
261
262         /* new mapping is needed */
263         idc = osd_idc_add(env, osd, fid);
264         if (IS_ERR(idc))
265                 return idc;
266
267         /* initialize it */
268         rc = osd_remote_fid(env, osd, fid);
269         if (unlikely(rc < 0))
270                 return ERR_PTR(rc);
271
272         if (rc == 0) {
273                 /* the object is local, lookup in OI */
274                 /* XXX: probably cheaper to lookup in LU first? */
275                 rc = osd_oi_lookup(osd_oti_get(env), osd, fid,
276                                    &idc->oic_lid, 0);
277                 if (unlikely(rc < 0)) {
278                         CERROR("can't lookup: rc = %d\n", rc);
279                         return ERR_PTR(rc);
280                 }
281         } else {
282                 /* the object is remote */
283                 idc->oic_remote = 1;
284         }
285
286         return idc;
287 }
288
289 /*
290  * lookup mapping for given FID and fill it from the given object.
291  * the object is lolcal by definition.
292  */
293 static int osd_idc_find_and_init(const struct lu_env *env,
294                                  struct osd_device *osd,
295                                  struct osd_object *obj)
296 {
297         const struct lu_fid     *fid = lu_object_fid(&obj->oo_dt.do_lu);
298         struct osd_idmap_cache  *idc;
299
300         idc = osd_idc_find(env, osd, fid);
301         LASSERT(!IS_ERR(idc));
302         if (idc != NULL) {
303                 if (obj->oo_inode == NULL)
304                         return 0;
305                 if (idc->oic_lid.oii_ino != obj->oo_inode->i_ino) {
306                         LASSERT(idc->oic_lid.oii_ino == 0);
307                         idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
308                         idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
309                 }
310                 return 0;
311         }
312
313         /* new mapping is needed */
314         idc = osd_idc_add(env, osd, fid);
315         if (IS_ERR(idc))
316                 return PTR_ERR(idc);
317
318         if (obj->oo_inode != NULL) {
319                 idc->oic_lid.oii_ino = obj->oo_inode->i_ino;
320                 idc->oic_lid.oii_gen = obj->oo_inode->i_generation;
321         }
322         return 0;
323 }
324
325 /*
326  * OSD object methods.
327  */
328
329 /*
330  * Concurrency: no concurrent access is possible that early in object
331  * life-cycle.
332  */
333 static struct lu_object *osd_object_alloc(const struct lu_env *env,
334                                           const struct lu_object_header *hdr,
335                                           struct lu_device *d)
336 {
337         struct osd_object *mo;
338
339         OBD_ALLOC_PTR(mo);
340         if (mo != NULL) {
341                 struct lu_object *l;
342
343                 l = &mo->oo_dt.do_lu;
344                 dt_object_init(&mo->oo_dt, NULL, d);
345                 mo->oo_dt.do_ops = &osd_obj_ea_ops;
346                 l->lo_ops = &osd_lu_obj_ops;
347                 init_rwsem(&mo->oo_sem);
348                 init_rwsem(&mo->oo_ext_idx_sem);
349                 spin_lock_init(&mo->oo_guard);
350                 return l;
351         } else {
352                 return NULL;
353         }
354 }
355
356 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
357                 struct dentry *dentry, struct lustre_mdt_attrs *lma)
358 {
359         int rc;
360
361         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
362         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
363                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
364         if (rc > 0) {
365                 if ((void *)lma != (void *)info->oti_mdt_attrs_old)
366                         memcpy(lma, info->oti_mdt_attrs_old, sizeof(*lma));
367                 rc = 0;
368                 lustre_lma_swab(lma);
369                 /* Check LMA compatibility */
370                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
371                         CWARN("%.16s: unsupported incompat LMA feature(s) %#x "
372                               "for fid = "DFID", ino = %lu\n",
373                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
374                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
375                               PFID(&lma->lma_self_fid), inode->i_ino);
376                         rc = -EOPNOTSUPP;
377                 }
378         } else if (rc == 0) {
379                 rc = -ENODATA;
380         }
381
382         return rc;
383 }
384
385 /*
386  * retrieve object from backend ext fs.
387  **/
388 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
389                        struct osd_inode_id *id)
390 {
391         struct inode *inode = NULL;
392
393         /* if we look for an inode withing a running
394          * transaction, then we risk to deadlock */
395         /* osd_dirent_check_repair() breaks this */
396         /*LASSERT(current->journal_info == NULL);*/
397
398         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
399         if (IS_ERR(inode)) {
400                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
401                        id->oii_ino, PTR_ERR(inode));
402         } else if (id->oii_gen != OSD_OII_NOGEN &&
403                    inode->i_generation != id->oii_gen) {
404                 CDEBUG(D_INODE, "unmatched inode: ino = %u, oii_gen = %u, "
405                        "i_generation = %u\n",
406                        id->oii_ino, id->oii_gen, inode->i_generation);
407                 iput(inode);
408                 inode = ERR_PTR(-ESTALE);
409         } else if (inode->i_nlink == 0) {
410                 /* due to parallel readdir and unlink,
411                 * we can have dead inode here. */
412                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
413                 iput(inode);
414                 inode = ERR_PTR(-ESTALE);
415         } else if (is_bad_inode(inode)) {
416                 CWARN("%.16s: bad inode: ino = %u\n",
417                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
418                 iput(inode);
419                 inode = ERR_PTR(-ENOENT);
420         } else {
421                 ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
422                 if (id->oii_gen == OSD_OII_NOGEN)
423                         osd_id_gen(id, inode->i_ino, inode->i_generation);
424
425                 /* Do not update file c/mtime in ldiskfs.
426                  * NB: we don't have any lock to protect this because we don't
427                  * have reference on osd_object now, but contention with
428                  * another lookup + attr_set can't happen in the tiny window
429                  * between if (...) and set S_NOCMTIME. */
430                 if (!(inode->i_flags & S_NOCMTIME))
431                         inode->i_flags |= S_NOCMTIME;
432         }
433         return inode;
434 }
435
436 int osd_ldiskfs_add_entry(struct osd_thread_info *info,
437                           handle_t *handle, struct dentry *child,
438                           struct inode *inode, struct htree_lock *hlock)
439 {
440         int rc, rc2;
441
442         rc = __ldiskfs_add_entry(handle, child, inode, hlock);
443         if (rc == -ENOBUFS || rc == -ENOSPC) {
444                 char fidbuf[FID_LEN + 1];
445                 struct lustre_mdt_attrs lma;
446                 struct lu_fid fid = { };
447                 char *errstr;
448                 struct dentry *p_dentry = child->d_parent;
449
450                 rc2 = osd_get_lma(info, p_dentry->d_inode, p_dentry,
451                                  &lma);
452                 if (rc2 == 0) {
453                         fid = lma.lma_self_fid;
454                         snprintf(fidbuf, sizeof(fidbuf), DFID, PFID(&fid));
455                 } else if (rc2 == -ENODATA) {
456                         if (unlikely(p_dentry->d_inode ==
457                                      inode->i_sb->s_root->d_inode))
458                                 lu_local_obj_fid(&fid, OSD_FS_ROOT_OID);
459                         else if (info->oti_dev && !info->oti_dev->od_is_ost &&
460                                  fid_seq_is_mdt0(fid_seq(&fid)))
461                                 lu_igif_build(&fid, p_dentry->d_inode->i_ino,
462                                               p_dentry->d_inode->i_generation);
463                         snprintf(fidbuf, sizeof(fidbuf), DFID, PFID(&fid));
464                 } else {
465                         snprintf(fidbuf, FID_LEN, "%s", "unknown");
466                 }
467
468                 if (rc == -ENOSPC)
469                         errstr = "has reached";
470                 else
471                         errstr = "is approaching";
472                 CWARN("%.16s: directory (inode: %lu FID: %s) %s maximum entry limit\n",
473                         LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
474                         p_dentry->d_inode->i_ino, fidbuf, errstr);
475                 /* ignore such error now */
476                 if (rc == -ENOBUFS)
477                         rc = 0;
478         }
479         return rc;
480 }
481
482
483 static struct inode *
484 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
485              struct osd_inode_id *id, struct lu_fid *fid)
486 {
487         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
488         struct inode            *inode;
489         int                      rc;
490
491         inode = osd_iget(info, dev, id);
492         if (IS_ERR(inode))
493                 return inode;
494
495         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
496         if (rc == 0) {
497                 *fid = lma->lma_self_fid;
498         } else if (rc == -ENODATA) {
499                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
500                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
501                 else
502                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
503         } else {
504                 iput(inode);
505                 inode = ERR_PTR(rc);
506         }
507         return inode;
508 }
509
510 static struct inode *osd_iget_check(struct osd_thread_info *info,
511                                     struct osd_device *dev,
512                                     const struct lu_fid *fid,
513                                     struct osd_inode_id *id,
514                                     bool cached)
515 {
516         struct inode    *inode;
517         int              rc     = 0;
518         ENTRY;
519
520         /* The cached OI mapping is trustable. If we cannot locate the inode
521          * via the cached OI mapping, then return the failure to the caller
522          * directly without further OI checking. */
523
524         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
525         if (IS_ERR(inode)) {
526                 rc = PTR_ERR(inode);
527                 if (cached || (rc != -ENOENT && rc != -ESTALE)) {
528                         CDEBUG(D_INODE, "no inode: ino = %u, rc = %d\n",
529                                id->oii_ino, rc);
530
531                         GOTO(put, rc);
532                 }
533
534                 goto check_oi;
535         }
536
537         if (is_bad_inode(inode)) {
538                 rc = -ENOENT;
539                 if (cached) {
540                         CDEBUG(D_INODE, "bad inode: ino = %u\n", id->oii_ino);
541
542                         GOTO(put, rc);
543                 }
544
545                 goto check_oi;
546         }
547
548         if (id->oii_gen != OSD_OII_NOGEN &&
549             inode->i_generation != id->oii_gen) {
550                 rc = -ESTALE;
551                 if (cached) {
552                         CDEBUG(D_INODE, "unmatched inode: ino = %u, "
553                                "oii_gen = %u, i_generation = %u\n",
554                                id->oii_ino, id->oii_gen, inode->i_generation);
555
556                         GOTO(put, rc);
557                 }
558
559                 goto check_oi;
560         }
561
562         if (inode->i_nlink == 0) {
563                 rc = -ENOENT;
564                 if (cached) {
565                         CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
566
567                         GOTO(put, rc);
568                 }
569
570                 goto check_oi;
571         }
572
573         ldiskfs_clear_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
574
575 check_oi:
576         if (rc != 0) {
577                 LASSERTF(rc == -ESTALE || rc == -ENOENT, "rc = %d\n", rc);
578
579                 rc = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
580                 /* XXX: There are four possible cases:
581                  *      1. rc = 0.
582                  *         Backup/restore caused the OI invalid.
583                  *      2. rc = 0.
584                  *         Someone unlinked the object but NOT removed
585                  *         the OI mapping, such as mount target device
586                  *         as ldiskfs, and modify something directly.
587                  *      3. rc = -ENOENT.
588                  *         Someone just removed the object between the
589                  *         former oi_lookup and the iget. It is normal.
590                  *      4. Other failure cases.
591                  *
592                  *      Generally, when the device is mounted, it will
593                  *      auto check whether the system is restored from
594                  *      file-level backup or not. We trust such detect
595                  *      to distinguish the 1st case from the 2nd case. */
596                 if (rc == 0) {
597                         if (!IS_ERR(inode) && inode->i_generation != 0 &&
598                             inode->i_generation == id->oii_gen)
599                                 /* "id->oii_gen != OSD_OII_NOGEN" is for
600                                  * "@cached == false" case. */
601                                 rc = -ENOENT;
602                         else
603                                 rc = -EREMCHG;
604                 } else {
605                         /* If the OI mapping was in OI file before the
606                          * osd_iget_check(), but now, it is disappear,
607                          * then it must be removed by race. That is a
608                          * normal race case. */
609                 }
610         } else {
611                 if (id->oii_gen == OSD_OII_NOGEN)
612                         osd_id_gen(id, inode->i_ino, inode->i_generation);
613
614                 /* Do not update file c/mtime in ldiskfs.
615                  * NB: we don't have any lock to protect this because we don't
616                  * have reference on osd_object now, but contention with
617                  * another lookup + attr_set can't happen in the tiny window
618                  * between if (...) and set S_NOCMTIME. */
619                 if (!(inode->i_flags & S_NOCMTIME))
620                         inode->i_flags |= S_NOCMTIME;
621         }
622
623         GOTO(put, rc);
624
625 put:
626         if (rc != 0) {
627                 if (!IS_ERR(inode))
628                         iput(inode);
629
630                 inode = ERR_PTR(rc);
631         }
632
633         return inode;
634 }
635
636 /**
637  * \retval +v: new filter_fid, does not contain self-fid
638  * \retval 0:  filter_fid_old, contains self-fid
639  * \retval -v: other failure cases
640  */
641 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
642                  struct dentry *dentry, struct lu_fid *fid)
643 {
644         struct filter_fid_old   *ff     = &info->oti_ff;
645         struct ost_id           *ostid  = &info->oti_ostid;
646         int                      rc;
647
648         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
649         if (rc == sizeof(*ff)) {
650                 rc = 0;
651                 ostid_set_seq(ostid, le64_to_cpu(ff->ff_seq));
652                 ostid_set_id(ostid, le64_to_cpu(ff->ff_objid));
653                 /* XXX: use 0 as the index for compatibility, the caller will
654                  *      handle index related issues when necessarry. */
655                 ostid_to_fid(fid, ostid, 0);
656         } else if (rc == sizeof(struct filter_fid)) {
657                 rc = 1;
658         } else if (rc >= 0) {
659                 rc = -EINVAL;
660         }
661
662         return rc;
663 }
664
665 static int osd_lma_self_repair(struct osd_thread_info *info,
666                                struct osd_device *osd, struct inode *inode,
667                                const struct lu_fid *fid, __u32 compat)
668 {
669         handle_t *jh;
670         int       rc;
671
672         LASSERT(current->journal_info == NULL);
673
674         jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC,
675                                   osd_dto_credits_noquota[DTO_XATTR_SET]);
676         if (IS_ERR(jh)) {
677                 rc = PTR_ERR(jh);
678                 CWARN("%s: cannot start journal for lma_self_repair: rc = %d\n",
679                       osd_name(osd), rc);
680                 return rc;
681         }
682
683         rc = osd_ea_fid_set(info, inode, fid, compat, 0);
684         if (rc != 0)
685                 CWARN("%s: cannot self repair the LMA: rc = %d\n",
686                       osd_name(osd), rc);
687         ldiskfs_journal_stop(jh);
688         return rc;
689 }
690
691 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
692 {
693         struct osd_thread_info  *info   = osd_oti_get(env);
694         struct osd_device       *osd    = osd_obj2dev(obj);
695         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
696         struct inode            *inode  = obj->oo_inode;
697         struct dentry           *dentry = &info->oti_obj_dentry;
698         struct lu_fid           *fid    = NULL;
699         const struct lu_fid     *rfid   = lu_object_fid(&obj->oo_dt.do_lu);
700         int                      rc;
701         ENTRY;
702
703         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
704         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
705                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
706         if (rc == -ENODATA && !fid_is_igif(rfid) && osd->od_check_ff) {
707                 fid = &lma->lma_self_fid;
708                 rc = osd_get_idif(info, inode, dentry, fid);
709                 if ((rc > 0) || (rc == -ENODATA && osd->od_index_in_idif)) {
710                         /* For the given OST-object, if it has neither LMA nor
711                          * FID in XATTR_NAME_FID, then the given FID (which is
712                          * contained in the @obj, from client RPC for locating
713                          * the OST-object) is trusted. We use it to generate
714                          * the LMA. */
715                         osd_lma_self_repair(info, osd, inode, rfid,
716                                             LMAC_FID_ON_OST);
717                         RETURN(0);
718                 }
719         }
720
721         if (rc < 0)
722                 RETURN(rc);
723
724         if (rc > 0) {
725                 rc = 0;
726                 lustre_lma_swab(lma);
727                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
728                              CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT))) {
729                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
730                               "fid = "DFID", ino = %lu\n", osd_name(osd),
731                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
732                               PFID(rfid), inode->i_ino);
733                         rc = -EOPNOTSUPP;
734                 } else {
735                         fid = &lma->lma_self_fid;
736                 }
737         }
738
739         if (fid != NULL && unlikely(!lu_fid_eq(rfid, fid))) {
740                 if (fid_is_idif(rfid) && fid_is_idif(fid)) {
741                         struct ost_id   *oi   = &info->oti_ostid;
742                         struct lu_fid   *fid1 = &info->oti_fid3;
743                         __u32            idx  = fid_idif_ost_idx(rfid);
744
745                         /* For old IDIF, the OST index is not part of the IDIF,
746                          * Means that different OSTs may have the same IDIFs.
747                          * Under such case, we need to make some compatible
748                          * check to make sure to trigger OI scrub properly. */
749                         if (idx != 0 && fid_idif_ost_idx(fid) == 0) {
750                                 /* Given @rfid is new, LMA is old. */
751                                 fid_to_ostid(fid, oi);
752                                 ostid_to_fid(fid1, oi, idx);
753                                 if (lu_fid_eq(fid1, rfid)) {
754                                         if (osd->od_index_in_idif)
755                                                 osd_lma_self_repair(info, osd,
756                                                         inode, rfid,
757                                                         LMAC_FID_ON_OST);
758                                         RETURN(0);
759                                 }
760                         }
761                 }
762
763                 rc = -EREMCHG;
764         }
765
766         RETURN(rc);
767 }
768
769 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
770                           const struct lu_fid *fid,
771                           const struct lu_object_conf *conf)
772 {
773         struct osd_thread_info *info;
774         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
775         struct osd_device      *dev;
776         struct osd_idmap_cache *oic;
777         struct osd_inode_id    *id;
778         struct inode           *inode;
779         struct osd_scrub       *scrub;
780         struct scrub_file      *sf;
781         int                     result;
782         int                     saved  = 0;
783         bool                    cached  = true;
784         bool                    triggered = false;
785         ENTRY;
786
787         LINVRNT(osd_invariant(obj));
788         LASSERT(obj->oo_inode == NULL);
789         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID"\n", PFID(fid));
790
791         dev = osd_dev(ldev);
792         scrub = &dev->od_scrub;
793         sf = &scrub->os_file;
794         info = osd_oti_get(env);
795         LASSERT(info);
796         oic = &info->oti_cache;
797
798         if (OBD_FAIL_CHECK(OBD_FAIL_SRV_ENOENT))
799                 RETURN(-ENOENT);
800
801         /* For the object is created as locking anchor, or for the object to
802          * be created on disk. No need to osd_oi_lookup() at here because FID
803          * shouldn't never be re-used, if it's really a duplicate FID from
804          * unexpected reason, we should be able to detect it later by calling
805          * do_create->osd_oi_insert(). */
806         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
807                 GOTO(out, result = 0);
808
809         /* Search order: 1. per-thread cache. */
810         if (lu_fid_eq(fid, &oic->oic_fid) &&
811             likely(oic->oic_dev == dev)) {
812                 id = &oic->oic_lid;
813                 goto iget;
814         }
815
816         id = &info->oti_id;
817         if (!list_empty(&scrub->os_inconsistent_items)) {
818                 /* Search order: 2. OI scrub pending list. */
819                 result = osd_oii_lookup(dev, fid, id);
820                 if (result == 0)
821                         goto iget;
822         }
823
824         cached = false;
825         /* Search order: 3. OI files. */
826         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
827         if (result == -ENOENT) {
828                 if (!(fid_is_norm(fid) || fid_is_igif(fid)) ||
829                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
830                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
831                                       sf->sf_oi_bitmap))
832                         GOTO(out, result = 0);
833
834                 goto trigger;
835         }
836
837         if (result != 0)
838                 GOTO(out, result);
839
840 iget:
841         inode = osd_iget_check(info, dev, fid, id, cached);
842         if (IS_ERR(inode)) {
843                 result = PTR_ERR(inode);
844                 if (result == -ENOENT || result == -ESTALE)
845                         GOTO(out, result = -ENOENT);
846
847                 if (result == -EREMCHG) {
848
849 trigger:
850                         if (unlikely(triggered))
851                                 GOTO(out, result = saved);
852
853                         triggered = true;
854                         if (thread_is_running(&scrub->os_thread)) {
855                                 result = -EINPROGRESS;
856                         } else if (!dev->od_noscrub) {
857                                 result = osd_scrub_start(dev, SS_AUTO_FULL |
858                                         SS_CLEAR_DRYRUN | SS_CLEAR_FAILOUT);
859                                 LCONSOLE_WARN("%.16s: trigger OI scrub by RPC "
860                                               "for "DFID", rc = %d [1]\n",
861                                               osd_name(dev), PFID(fid), result);
862                                 if (result == 0 || result == -EALREADY)
863                                         result = -EINPROGRESS;
864                                 else
865                                         result = -EREMCHG;
866                         } else {
867                                 result = -EREMCHG;
868                         }
869
870                         if (fid_is_on_ost(info, dev, fid, OI_CHECK_FLD))
871                                 GOTO(out, result);
872
873                         /* We still have chance to get the valid inode: for the
874                          * object which is referenced by remote name entry, the
875                          * object on the local MDT will be linked under the dir
876                          * of "/REMOTE_PARENT_DIR" with its FID string as name.
877                          *
878                          * We do not know whether the object for the given FID
879                          * is referenced by some remote name entry or not, and
880                          * especially for DNE II, a multiple-linked object may
881                          * have many name entries reside on many MDTs.
882                          *
883                          * To simplify the operation, OSD will not distinguish
884                          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
885                          * only happened for the RPC from other MDT during the
886                          * OI scrub, or for the client side RPC with FID only,
887                          * such as FID to path, or from old connected client. */
888                         saved = result;
889                         result = osd_lookup_in_remote_parent(info, dev,
890                                                              fid, id);
891                         if (result == 0) {
892                                 cached = true;
893                                 goto iget;
894                         }
895
896                         result = saved;
897                 }
898
899                 GOTO(out, result);
900         }
901
902         obj->oo_inode = inode;
903         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
904
905         result = osd_check_lma(env, obj);
906         if (result != 0) {
907                 if (result == -ENODATA) {
908                         if (cached) {
909                                 result = osd_oi_lookup(info, dev, fid, id,
910                                                        OI_CHECK_FLD);
911                                 if (result != 0) {
912                                         /* result == -ENOENT means that the OI
913                                          * mapping has been removed by race,
914                                          * the target inode belongs to other
915                                          * object.
916                                          *
917                                          * Others error also can be returned
918                                          * directly. */
919                                         iput(inode);
920                                         obj->oo_inode = NULL;
921                                         GOTO(out, result);
922                                 } else {
923                                         /* result == 0 means the cached OI
924                                          * mapping is still in the OI file,
925                                          * the target the inode is valid. */
926                                 }
927                         } else {
928                                 /* The current OI mapping is from the OI file,
929                                  * since the inode has been found via
930                                  * osd_iget_check(), no need recheck OI. */
931                         }
932
933                         goto found;
934                 }
935
936                 iput(inode);
937                 obj->oo_inode = NULL;
938                 if (result != -EREMCHG)
939                         GOTO(out, result);
940
941                 if (cached) {
942                         result = osd_oi_lookup(info, dev, fid, id,
943                                                OI_CHECK_FLD);
944                         /* result == -ENOENT means the cached OI mapping
945                          * has been removed from the OI file by race,
946                          * above target inode belongs to other object.
947                          *
948                          * Others error also can be returned directly. */
949                         if (result != 0)
950                                 GOTO(out, result);
951
952                         /* result == 0, goto trigger */
953                 } else {
954                         /* The current OI mapping is from the OI file,
955                          * since the inode has been found via
956                          * osd_iget_check(), no need recheck OI. */
957                 }
958
959                 goto trigger;
960         }
961
962 found:
963         obj->oo_compat_dot_created = 1;
964         obj->oo_compat_dotdot_created = 1;
965
966         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
967                 GOTO(out, result = 0);
968
969         LASSERT(obj->oo_hl_head == NULL);
970         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
971         if (obj->oo_hl_head == NULL) {
972                 obj->oo_inode = NULL;
973                 iput(inode);
974                 GOTO(out, result = -ENOMEM);
975         }
976         GOTO(out, result = 0);
977
978 out:
979         if (result != 0 && cached)
980                 fid_zero(&oic->oic_fid);
981
982         LINVRNT(osd_invariant(obj));
983         return result;
984 }
985
986 /*
987  * Concurrency: shouldn't matter.
988  */
989 static void osd_object_init0(struct osd_object *obj)
990 {
991         LASSERT(obj->oo_inode != NULL);
992         obj->oo_dt.do_body_ops = &osd_body_ops;
993         obj->oo_dt.do_lu.lo_header->loh_attr |=
994                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
995 }
996
997 /*
998  * Concurrency: no concurrent access is possible that early in object
999  * life-cycle.
1000  */
1001 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
1002                            const struct lu_object_conf *conf)
1003 {
1004         struct osd_object *obj = osd_obj(l);
1005         int result;
1006
1007         LINVRNT(osd_invariant(obj));
1008
1009         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
1010                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
1011                 l->lo_header->loh_attr |= LOHA_EXISTS;
1012                 return 0;
1013         }
1014
1015         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
1016         obj->oo_dt.do_body_ops = &osd_body_ops_new;
1017         if (result == 0 && obj->oo_inode != NULL) {
1018                 struct osd_thread_info *oti = osd_oti_get(env);
1019                 struct lustre_mdt_attrs *lma = &oti->oti_mdt_attrs;
1020
1021                 osd_object_init0(obj);
1022                 result = osd_get_lma(oti, obj->oo_inode,
1023                                      &oti->oti_obj_dentry, lma);
1024                 if (result == 0) {
1025                         /* Convert LMAI flags to lustre LMA flags
1026                          * and cache it to oo_lma_flags */
1027                         obj->oo_lma_flags =
1028                                 lma_to_lustre_flags(lma->lma_incompat);
1029                 } else if (result == -ENODATA) {
1030                         result = 0;
1031                 }
1032         }
1033
1034         LINVRNT(osd_invariant(obj));
1035         return result;
1036 }
1037
1038 /*
1039  * Concurrency: no concurrent access is possible that late in object
1040  * life-cycle.
1041  */
1042 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
1043 {
1044         struct osd_object *obj = osd_obj(l);
1045
1046         LINVRNT(osd_invariant(obj));
1047
1048         dt_object_fini(&obj->oo_dt);
1049         if (obj->oo_hl_head != NULL)
1050                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1051         OBD_FREE_PTR(obj);
1052 }
1053
1054 /*
1055  * Concurrency: no concurrent access is possible that late in object
1056  * life-cycle.
1057  */
1058 static void osd_index_fini(struct osd_object *o)
1059 {
1060         struct iam_container *bag;
1061
1062         if (o->oo_dir != NULL) {
1063                 bag = &o->oo_dir->od_container;
1064                 if (o->oo_inode != NULL) {
1065                         if (bag->ic_object == o->oo_inode)
1066                                 iam_container_fini(bag);
1067                 }
1068                 OBD_FREE_PTR(o->oo_dir);
1069                 o->oo_dir = NULL;
1070         }
1071 }
1072
1073 /*
1074  * Concurrency: no concurrent access is possible that late in object
1075  * life-cycle (for all existing callers, that is. New callers have to provide
1076  * their own locking.)
1077  */
1078 static int osd_inode_unlinked(const struct inode *inode)
1079 {
1080         return inode->i_nlink == 0;
1081 }
1082
1083 enum {
1084         OSD_TXN_OI_DELETE_CREDITS    = 20,
1085         OSD_TXN_INODE_DELETE_CREDITS = 20
1086 };
1087
1088 /*
1089  * Journal
1090  */
1091
1092 #if OSD_THANDLE_STATS
1093 /**
1094  * Set time when the handle is allocated
1095  */
1096 static void osd_th_alloced(struct osd_thandle *oth)
1097 {
1098         oth->oth_alloced = cfs_time_current();
1099 }
1100
1101 /**
1102  * Set time when the handle started
1103  */
1104 static void osd_th_started(struct osd_thandle *oth)
1105 {
1106         oth->oth_started = cfs_time_current();
1107 }
1108
1109 /**
1110  * Helper function to convert time interval to microseconds packed in
1111  * long int.
1112  */
1113 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
1114 {
1115         struct timeval val;
1116
1117         cfs_duration_usec(cfs_time_sub(end, start), &val);
1118         return val.tv_sec * 1000000 + val.tv_usec;
1119 }
1120
1121 /**
1122  * Check whether the we deal with this handle for too long.
1123  */
1124 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
1125                                 cfs_time_t alloced, cfs_time_t started,
1126                                 cfs_time_t closed)
1127 {
1128         cfs_time_t now = cfs_time_current();
1129
1130         LASSERT(dev != NULL);
1131
1132         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
1133                             interval_to_usec(alloced, started));
1134         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
1135                             interval_to_usec(started, closed));
1136         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
1137                             interval_to_usec(closed, now));
1138
1139         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
1140                 CWARN("transaction handle %p was open for too long: "
1141                       "now "CFS_TIME_T" ,"
1142                       "alloced "CFS_TIME_T" ,"
1143                       "started "CFS_TIME_T" ,"
1144                       "closed "CFS_TIME_T"\n",
1145                       oth, now, alloced, started, closed);
1146                 libcfs_debug_dumpstack(NULL);
1147         }
1148 }
1149
1150 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
1151 {                                                                       \
1152         cfs_time_t __closed = cfs_time_current();                       \
1153         cfs_time_t __alloced = oth->oth_alloced;                        \
1154         cfs_time_t __started = oth->oth_started;                        \
1155                                                                         \
1156         expr;                                                           \
1157         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
1158 }
1159
1160 #else /* OSD_THANDLE_STATS */
1161
1162 #define osd_th_alloced(h)                  do {} while(0)
1163 #define osd_th_started(h)                  do {} while(0)
1164 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
1165
1166 #endif /* OSD_THANDLE_STATS */
1167
1168 /*
1169  * Concurrency: doesn't access mutable data.
1170  */
1171 static int osd_param_is_not_sane(const struct osd_device *dev,
1172                                  const struct thandle *th)
1173 {
1174         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
1175
1176         return oh->ot_credits > osd_transaction_size(dev);
1177 }
1178
1179 /*
1180  * Concurrency: shouldn't matter.
1181  */
1182 static void osd_trans_commit_cb(struct super_block *sb,
1183                                 struct ldiskfs_journal_cb_entry *jcb, int error)
1184 {
1185         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
1186         struct thandle     *th  = &oh->ot_super;
1187         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
1188         struct dt_txn_commit_cb *dcb, *tmp;
1189
1190         LASSERT(oh->ot_handle == NULL);
1191
1192         if (error)
1193                 CERROR("transaction @0x%p commit error: %d\n", th, error);
1194
1195         dt_txn_hook_commit(th);
1196
1197         /* call per-transaction callbacks if any */
1198         list_for_each_entry_safe(dcb, tmp, &oh->ot_commit_dcb_list,
1199                                  dcb_linkage) {
1200                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1201                          "commit callback entry: magic=%x name='%s'\n",
1202                          dcb->dcb_magic, dcb->dcb_name);
1203                 list_del_init(&dcb->dcb_linkage);
1204                 dcb->dcb_func(NULL, th, dcb, error);
1205         }
1206
1207         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
1208         lu_device_put(lud);
1209         th->th_dev = NULL;
1210
1211         lu_context_exit(&th->th_ctx);
1212         lu_context_fini(&th->th_ctx);
1213         OBD_FREE_PTR(oh);
1214 }
1215
1216 static struct thandle *osd_trans_create(const struct lu_env *env,
1217                                         struct dt_device *d)
1218 {
1219         struct osd_thread_info  *oti = osd_oti_get(env);
1220         struct osd_iobuf        *iobuf = &oti->oti_iobuf;
1221         struct osd_thandle      *oh;
1222         struct thandle          *th;
1223         ENTRY;
1224
1225         /* on pending IO in this thread should left from prev. request */
1226         LASSERT(atomic_read(&iobuf->dr_numreqs) == 0);
1227
1228         th = ERR_PTR(-ENOMEM);
1229         OBD_ALLOC_GFP(oh, sizeof *oh, GFP_NOFS);
1230         if (oh != NULL) {
1231                 oh->ot_quota_trans = &oti->oti_quota_trans;
1232                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
1233                 th = &oh->ot_super;
1234                 th->th_dev = d;
1235                 th->th_result = 0;
1236                 th->th_tags = LCT_TX_HANDLE;
1237                 oh->ot_credits = 0;
1238                 INIT_LIST_HEAD(&oh->ot_commit_dcb_list);
1239                 INIT_LIST_HEAD(&oh->ot_stop_dcb_list);
1240                 osd_th_alloced(oh);
1241
1242                 memset(oti->oti_declare_ops, 0,
1243                        sizeof(oti->oti_declare_ops));
1244                 memset(oti->oti_declare_ops_cred, 0,
1245                        sizeof(oti->oti_declare_ops_cred));
1246                 memset(oti->oti_declare_ops_used, 0,
1247                        sizeof(oti->oti_declare_ops_used));
1248         }
1249         RETURN(th);
1250 }
1251
1252 void osd_trans_dump_creds(const struct lu_env *env, struct thandle *th)
1253 {
1254         struct osd_thread_info  *oti = osd_oti_get(env);
1255         struct osd_thandle      *oh;
1256
1257         oh = container_of0(th, struct osd_thandle, ot_super);
1258         LASSERT(oh != NULL);
1259
1260         CWARN("  create: %u/%u/%u, destroy: %u/%u/%u\n",
1261               oti->oti_declare_ops[OSD_OT_CREATE],
1262               oti->oti_declare_ops_cred[OSD_OT_CREATE],
1263               oti->oti_declare_ops_used[OSD_OT_CREATE],
1264               oti->oti_declare_ops[OSD_OT_DESTROY],
1265               oti->oti_declare_ops_cred[OSD_OT_DESTROY],
1266               oti->oti_declare_ops_used[OSD_OT_DESTROY]);
1267         CWARN("  attr_set: %u/%u/%u, xattr_set: %u/%u/%u\n",
1268               oti->oti_declare_ops[OSD_OT_ATTR_SET],
1269               oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
1270               oti->oti_declare_ops_used[OSD_OT_ATTR_SET],
1271               oti->oti_declare_ops[OSD_OT_XATTR_SET],
1272               oti->oti_declare_ops_cred[OSD_OT_XATTR_SET],
1273               oti->oti_declare_ops_used[OSD_OT_XATTR_SET]);
1274         CWARN("  write: %u/%u/%u, punch: %u/%u/%u, quota %u/%u/%u\n",
1275               oti->oti_declare_ops[OSD_OT_WRITE],
1276               oti->oti_declare_ops_cred[OSD_OT_WRITE],
1277               oti->oti_declare_ops_used[OSD_OT_WRITE],
1278               oti->oti_declare_ops[OSD_OT_PUNCH],
1279               oti->oti_declare_ops_cred[OSD_OT_PUNCH],
1280               oti->oti_declare_ops_used[OSD_OT_PUNCH],
1281               oti->oti_declare_ops[OSD_OT_QUOTA],
1282               oti->oti_declare_ops_cred[OSD_OT_QUOTA],
1283               oti->oti_declare_ops_used[OSD_OT_QUOTA]);
1284         CWARN("  insert: %u/%u/%u, delete: %u/%u/%u\n",
1285               oti->oti_declare_ops[OSD_OT_INSERT],
1286               oti->oti_declare_ops_cred[OSD_OT_INSERT],
1287               oti->oti_declare_ops_used[OSD_OT_INSERT],
1288               oti->oti_declare_ops[OSD_OT_DELETE],
1289               oti->oti_declare_ops_cred[OSD_OT_DELETE],
1290               oti->oti_declare_ops_used[OSD_OT_DELETE]);
1291         CWARN("  ref_add: %u/%u/%u, ref_del: %u/%u/%u\n",
1292               oti->oti_declare_ops[OSD_OT_REF_ADD],
1293               oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
1294               oti->oti_declare_ops_used[OSD_OT_REF_ADD],
1295               oti->oti_declare_ops[OSD_OT_REF_DEL],
1296               oti->oti_declare_ops_cred[OSD_OT_REF_DEL],
1297               oti->oti_declare_ops_used[OSD_OT_REF_DEL]);
1298 }
1299
1300 /*
1301  * Concurrency: shouldn't matter.
1302  */
1303 static int osd_trans_start(const struct lu_env *env, struct dt_device *d,
1304                            struct thandle *th)
1305 {
1306         struct osd_thread_info *oti = osd_oti_get(env);
1307         struct osd_device  *dev = osd_dt_dev(d);
1308         handle_t           *jh;
1309         struct osd_thandle *oh;
1310         int rc;
1311
1312         ENTRY;
1313
1314         LASSERT(current->journal_info == NULL);
1315
1316         oh = container_of0(th, struct osd_thandle, ot_super);
1317         LASSERT(oh != NULL);
1318         LASSERT(oh->ot_handle == NULL);
1319
1320         rc = dt_txn_hook_start(env, d, th);
1321         if (rc != 0)
1322                 GOTO(out, rc);
1323
1324         if (unlikely(osd_param_is_not_sane(dev, th))) {
1325                 static unsigned long last_printed;
1326                 static int last_credits;
1327
1328                 /* don't make noise on a tiny testing systems
1329                  * actual credits misuse will be caught anyway */
1330                 if (last_credits != oh->ot_credits &&
1331                     time_after(jiffies, last_printed +
1332                                msecs_to_jiffies(60 * MSEC_PER_SEC)) &&
1333                     osd_transaction_size(dev) > 512) {
1334                         osd_trans_dump_creds(env, th);
1335                         libcfs_debug_dumpstack(NULL);
1336                         last_credits = oh->ot_credits;
1337                         last_printed = jiffies;
1338                 }
1339                 /* XXX Limit the credits to 'max_transaction_buffers', and
1340                  *     let the underlying filesystem to catch the error if
1341                  *     we really need so many credits.
1342                  *
1343                  *     This should be removed when we can calculate the
1344                  *     credits precisely. */
1345                 oh->ot_credits = osd_transaction_size(dev);
1346         }
1347
1348         /*
1349          * XXX temporary stuff. Some abstraction layer should
1350          * be used.
1351          */
1352         jh = osd_journal_start_sb(osd_sb(dev), LDISKFS_HT_MISC, oh->ot_credits);
1353         osd_th_started(oh);
1354         if (!IS_ERR(jh)) {
1355                 oh->ot_handle = jh;
1356                 LASSERT(oti->oti_txns == 0);
1357                 lu_context_init(&th->th_ctx, th->th_tags);
1358                 lu_context_enter(&th->th_ctx);
1359
1360                 lu_device_get(&d->dd_lu_dev);
1361                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
1362                               "osd-tx", th);
1363                 oti->oti_txns++;
1364                 rc = 0;
1365         } else {
1366                 rc = PTR_ERR(jh);
1367         }
1368 out:
1369         RETURN(rc);
1370 }
1371
1372 static int osd_seq_exists(const struct lu_env *env,
1373                           struct osd_device *osd, u64 seq)
1374 {
1375         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
1376         struct seq_server_site  *ss = osd_seq_site(osd);
1377         int                     rc;
1378         ENTRY;
1379
1380         LASSERT(ss != NULL);
1381         LASSERT(ss->ss_server_fld != NULL);
1382
1383         rc = osd_fld_lookup(env, osd, seq, range);
1384         if (rc != 0) {
1385                 if (rc != -ENOENT)
1386                         CERROR("%s: can't lookup FLD sequence "LPX64
1387                                ": rc = %d\n", osd_name(osd), seq, rc);
1388                 RETURN(0);
1389         }
1390
1391         RETURN(ss->ss_node_id == range->lsr_index);
1392 }
1393
1394 static void osd_trans_stop_cb(struct osd_thandle *oth, int result)
1395 {
1396         struct dt_txn_commit_cb *dcb;
1397         struct dt_txn_commit_cb *tmp;
1398
1399         /* call per-transaction stop callbacks if any */
1400         list_for_each_entry_safe(dcb, tmp, &oth->ot_stop_dcb_list,
1401                                  dcb_linkage) {
1402                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
1403                          "commit callback entry: magic=%x name='%s'\n",
1404                          dcb->dcb_magic, dcb->dcb_name);
1405                 list_del_init(&dcb->dcb_linkage);
1406                 dcb->dcb_func(NULL, &oth->ot_super, dcb, result);
1407         }
1408 }
1409
1410 /*
1411  * Concurrency: shouldn't matter.
1412  */
1413 static int osd_trans_stop(const struct lu_env *env, struct dt_device *dt,
1414                           struct thandle *th)
1415 {
1416         int                     rc = 0, remove_agents = 0;
1417         struct osd_thandle     *oh;
1418         struct osd_thread_info *oti = osd_oti_get(env);
1419         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
1420         struct osd_device      *osd = osd_dt_dev(th->th_dev);
1421         struct qsd_instance    *qsd = osd->od_quota_slave;
1422         struct lquota_trans    *qtrans;
1423         ENTRY;
1424
1425         oh = container_of0(th, struct osd_thandle, ot_super);
1426
1427         /* reset OI cache for safety */
1428         oti->oti_ins_cache_used = 0;
1429
1430         remove_agents = oh->ot_remove_agents;
1431
1432         qtrans = oh->ot_quota_trans;
1433         oh->ot_quota_trans = NULL;
1434
1435         if (oh->ot_handle != NULL) {
1436                 handle_t *hdl = oh->ot_handle;
1437
1438                 /*
1439                  * add commit callback
1440                  * notice we don't do this in osd_trans_start()
1441                  * as underlying transaction can change during truncate
1442                  */
1443                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
1444                                          &oh->ot_jcb);
1445
1446                 LASSERT(oti->oti_txns == 1);
1447                 oti->oti_txns--;
1448
1449                 rc = dt_txn_hook_stop(env, th);
1450                 if (rc != 0)
1451                         CERROR("%s: failed in transaction hook: rc = %d\n",
1452                                osd_name(osd), rc);
1453
1454                 osd_trans_stop_cb(oh, rc);
1455                 /* hook functions might modify th_sync */
1456                 hdl->h_sync = th->th_sync;
1457
1458                 oh->ot_handle = NULL;
1459                 OSD_CHECK_SLOW_TH(oh, osd, rc = ldiskfs_journal_stop(hdl));
1460                 if (rc != 0)
1461                         CERROR("%s: failed to stop transaction: rc = %d\n",
1462                                osd_name(osd), rc);
1463         } else {
1464                 osd_trans_stop_cb(oh, th->th_result);
1465                 OBD_FREE_PTR(oh);
1466         }
1467
1468         /* inform the quota slave device that the transaction is stopping */
1469         qsd_op_end(env, qsd, qtrans);
1470
1471         /* as we want IO to journal and data IO be concurrent, we don't block
1472          * awaiting data IO completion in osd_do_bio(), instead we wait here
1473          * once transaction is submitted to the journal. all reqular requests
1474          * don't do direct IO (except read/write), thus this wait_event becomes
1475          * no-op for them.
1476          *
1477          * IMPORTANT: we have to wait till any IO submited by the thread is
1478          * completed otherwise iobuf may be corrupted by different request
1479          */
1480         wait_event(iobuf->dr_wait,
1481                        atomic_read(&iobuf->dr_numreqs) == 0);
1482         osd_fini_iobuf(osd, iobuf);
1483         if (!rc)
1484                 rc = iobuf->dr_error;
1485
1486         if (unlikely(remove_agents != 0))
1487                 osd_process_scheduled_agent_removals(env, osd);
1488
1489         RETURN(rc);
1490 }
1491
1492 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
1493 {
1494         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
1495                                                ot_super);
1496
1497         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
1498         LASSERT(&dcb->dcb_func != NULL);
1499         if (dcb->dcb_flags & DCB_TRANS_STOP)
1500                 list_add(&dcb->dcb_linkage, &oh->ot_stop_dcb_list);
1501         else
1502                 list_add(&dcb->dcb_linkage, &oh->ot_commit_dcb_list);
1503
1504         return 0;
1505 }
1506
1507 /*
1508  * Called just before object is freed. Releases all resources except for
1509  * object itself (that is released by osd_object_free()).
1510  *
1511  * Concurrency: no concurrent access is possible that late in object
1512  * life-cycle.
1513  */
1514 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
1515 {
1516         struct osd_object *obj   = osd_obj(l);
1517         struct inode      *inode = obj->oo_inode;
1518
1519         LINVRNT(osd_invariant(obj));
1520
1521         /*
1522          * If object is unlinked remove fid->ino mapping from object index.
1523          */
1524
1525         osd_index_fini(obj);
1526         if (inode != NULL) {
1527                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
1528                 qid_t                    uid = i_uid_read(inode);
1529                 qid_t                    gid = i_gid_read(inode);
1530
1531                 iput(inode);
1532                 obj->oo_inode = NULL;
1533
1534                 if (qsd != NULL) {
1535                         struct osd_thread_info  *info = osd_oti_get(env);
1536                         struct lquota_id_info   *qi = &info->oti_qi;
1537
1538                         /* Release granted quota to master if necessary */
1539                         qi->lqi_id.qid_uid = uid;
1540                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
1541
1542                         qi->lqi_id.qid_uid = gid;
1543                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
1544                 }
1545         }
1546 }
1547
1548 /*
1549  * Concurrency: ->loo_object_release() is called under site spin-lock.
1550  */
1551 static void osd_object_release(const struct lu_env *env,
1552                                struct lu_object *l)
1553 {
1554         struct osd_object *o = osd_obj(l);
1555         /* nobody should be releasing a non-destroyed object with nlink=0
1556          * the API allows this, but ldiskfs doesn't like and then report
1557          * this inode as deleted */
1558         if (unlikely(!o->oo_destroyed && o->oo_inode && o->oo_inode->i_nlink == 0))
1559                 LBUG();
1560 }
1561
1562 /*
1563  * Concurrency: shouldn't matter.
1564  */
1565 static int osd_object_print(const struct lu_env *env, void *cookie,
1566                             lu_printer_t p, const struct lu_object *l)
1567 {
1568         struct osd_object *o = osd_obj(l);
1569         struct iam_descr  *d;
1570
1571         if (o->oo_dir != NULL)
1572                 d = o->oo_dir->od_container.ic_descr;
1573         else
1574                 d = NULL;
1575         return (*p)(env, cookie,
1576                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
1577                     o, o->oo_inode,
1578                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
1579                     o->oo_inode ? o->oo_inode->i_generation : 0,
1580                     d ? d->id_ops->id_name : "plain");
1581 }
1582
1583 /*
1584  * Concurrency: shouldn't matter.
1585  */
1586 int osd_statfs(const struct lu_env *env, struct dt_device *d,
1587                struct obd_statfs *sfs)
1588 {
1589         struct osd_device       *osd = osd_dt_dev(d);
1590         struct super_block      *sb = osd_sb(osd);
1591         struct kstatfs          *ksfs;
1592         __u64                    reserved;
1593         int                      result = 0;
1594
1595         if (unlikely(osd->od_mnt == NULL))
1596                 return -EINPROGRESS;
1597
1598         /* osd_lproc.c call this without env, allocate ksfs for that case */
1599         if (unlikely(env == NULL)) {
1600                 OBD_ALLOC_PTR(ksfs);
1601                 if (ksfs == NULL)
1602                         return -ENOMEM;
1603         } else {
1604                 ksfs = &osd_oti_get(env)->oti_ksfs;
1605         }
1606
1607         result = sb->s_op->statfs(sb->s_root, ksfs);
1608         if (result)
1609                 goto out;
1610
1611         statfs_pack(sfs, ksfs);
1612         if (unlikely(sb->s_flags & MS_RDONLY))
1613                 sfs->os_state = OS_STATE_READONLY;
1614         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb,
1615                                          LDISKFS_FEATURE_INCOMPAT_EXTENTS))
1616                 sfs->os_maxbytes = sb->s_maxbytes;
1617         else
1618                 sfs->os_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
1619
1620         /*
1621          * Reserve some space so to avoid fragmenting the filesystem too much.
1622          * Fragmentation not only impacts performance, but can also increase
1623          * metadata overhead significantly, causing grant calculation to be
1624          * wrong.
1625          *
1626          * Reserve 0.78% of total space, at least 8MB for small filesystems.
1627          */
1628         CLASSERT(OSD_STATFS_RESERVED > LDISKFS_MAX_BLOCK_SIZE);
1629         reserved = OSD_STATFS_RESERVED >> sb->s_blocksize_bits;
1630         if (likely(sfs->os_blocks >= reserved << OSD_STATFS_RESERVED_SHIFT))
1631                 reserved = sfs->os_blocks >> OSD_STATFS_RESERVED_SHIFT;
1632
1633         sfs->os_blocks -= reserved;
1634         sfs->os_bfree  -= min(reserved, sfs->os_bfree);
1635         sfs->os_bavail -= min(reserved, sfs->os_bavail);
1636
1637 out:
1638         if (unlikely(env == NULL))
1639                 OBD_FREE_PTR(ksfs);
1640         return result;
1641 }
1642
1643 /**
1644  * Estimate space needed for file creations. We assume the largest filename
1645  * which is 2^64 - 1, hence a filename of 20 chars.
1646  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
1647  */
1648 #ifdef __LDISKFS_DIR_REC_LEN
1649 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
1650 #else
1651 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
1652 #endif
1653
1654 /*
1655  * Concurrency: doesn't access mutable data.
1656  */
1657 static void osd_conf_get(const struct lu_env *env,
1658                          const struct dt_device *dev,
1659                          struct dt_device_param *param)
1660 {
1661         struct super_block *sb = osd_sb(osd_dt_dev(dev));
1662         int                ea_overhead;
1663
1664         /*
1665          * XXX should be taken from not-yet-existing fs abstraction layer.
1666          */
1667         param->ddp_max_name_len = LDISKFS_NAME_LEN;
1668         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
1669         param->ddp_symlink_max  = sb->s_blocksize;
1670         param->ddp_mount_type     = LDD_MT_LDISKFS;
1671         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EXTENTS))
1672                 param->ddp_maxbytes = sb->s_maxbytes;
1673         else
1674                 param->ddp_maxbytes = LDISKFS_SB(sb)->s_bitmap_maxbytes;
1675         /* inode are statically allocated, so per-inode space consumption
1676          * is the space consumed by the directory entry */
1677         param->ddp_inodespace     = PER_OBJ_USAGE;
1678         /* EXT_INIT_MAX_LEN is the theoretical maximum extent size  (32k blocks
1679          * = 128MB) which is unlikely to be hit in real life. Report a smaller
1680          * maximum length to not under count the actual number of extents
1681          * needed for writing a file. */
1682         param->ddp_max_extent_blks = EXT_INIT_MAX_LEN >> 2;
1683         /* worst-case extent insertion metadata overhead */
1684         param->ddp_extent_tax = 6 * LDISKFS_BLOCK_SIZE(sb);
1685         param->ddp_mntopts      = 0;
1686         if (test_opt(sb, XATTR_USER))
1687                 param->ddp_mntopts |= MNTOPT_USERXATTR;
1688         if (test_opt(sb, POSIX_ACL))
1689                 param->ddp_mntopts |= MNTOPT_ACL;
1690
1691         /* LOD might calculate the max stripe count based on max_ea_size,
1692          * so we need take account in the overhead as well,
1693          * xattr_header + magic + xattr_entry_head */
1694         ea_overhead = sizeof(struct ldiskfs_xattr_header) + sizeof(__u32) +
1695                       LDISKFS_XATTR_LEN(XATTR_NAME_MAX_LEN);
1696
1697 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
1698         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
1699                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE -
1700                                                                 ea_overhead;
1701         else
1702 #endif
1703                 param->ddp_max_ea_size = sb->s_blocksize - ea_overhead;
1704 }
1705
1706 /*
1707  * Concurrency: shouldn't matter.
1708  */
1709 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1710 {
1711         int rc;
1712
1713         CDEBUG(D_CACHE, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1714
1715         rc = ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1716
1717         CDEBUG(D_CACHE, "synced OSD %s: rc = %d\n",
1718                LUSTRE_OSD_LDISKFS_NAME, rc);
1719
1720         return rc;
1721 }
1722
1723 /**
1724  * Start commit for OSD device.
1725  *
1726  * An implementation of dt_commit_async method for OSD device.
1727  * Asychronously starts underlayng fs sync and thereby a transaction
1728  * commit.
1729  *
1730  * \param env environment
1731  * \param d dt device
1732  *
1733  * \see dt_device_operations
1734  */
1735 static int osd_commit_async(const struct lu_env *env,
1736                             struct dt_device *d)
1737 {
1738         struct super_block *s = osd_sb(osd_dt_dev(d));
1739         ENTRY;
1740
1741         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1742         RETURN(s->s_op->sync_fs(s, 0));
1743 }
1744
1745 /*
1746  * Concurrency: shouldn't matter.
1747  */
1748
1749 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1750 {
1751         struct super_block *sb = osd_sb(osd_dt_dev(d));
1752         struct block_device *dev = sb->s_bdev;
1753 #ifdef HAVE_DEV_SET_RDONLY
1754         struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
1755         int rc = 0;
1756 #else
1757         int rc = -EOPNOTSUPP;
1758 #endif
1759         ENTRY;
1760
1761 #ifdef HAVE_DEV_SET_RDONLY
1762         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1763
1764         if (jdev && (jdev != dev)) {
1765                 CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
1766                        (long)jdev);
1767                 dev_set_rdonly(jdev);
1768         }
1769         CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
1770         dev_set_rdonly(dev);
1771 #else
1772         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
1773                osd_dt_dev(d)->od_svname, (long)dev, rc);
1774 #endif
1775         RETURN(rc);
1776 }
1777
1778 /**
1779  * Note: we do not count into QUOTA here.
1780  * If we mount with --data_journal we may need more.
1781  */
1782 const int osd_dto_credits_noquota[DTO_NR] = {
1783         /**
1784          * Insert.
1785          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1786          * SINGLEDATA_TRANS_BLOCKS(8)
1787          * XXX Note: maybe iam need more, since iam have more level than
1788          *           EXT3 htree.
1789          */
1790         [DTO_INDEX_INSERT]  = 16,
1791         /**
1792          * Delete
1793          * just modify a single entry, probably merge few within a block
1794          */
1795         [DTO_INDEX_DELETE]  = 1,
1796         /**
1797          * Used for OI scrub
1798          */
1799         [DTO_INDEX_UPDATE]  = 16,
1800         /**
1801          * 4(inode, inode bits, groups, GDT)
1802          *   notice: OI updates are counted separately with DTO_INDEX_INSERT
1803          */
1804         [DTO_OBJECT_CREATE] = 4,
1805         /**
1806          * 4(inode, inode bits, groups, GDT)
1807          *   notice: OI updates are counted separately with DTO_INDEX_DELETE
1808          */
1809         [DTO_OBJECT_DELETE] = 4,
1810         /**
1811          * Attr set credits (inode)
1812          */
1813         [DTO_ATTR_SET_BASE] = 1,
1814         /**
1815          * Xattr set. The same as xattr of EXT3.
1816          * DATA_TRANS_BLOCKS(14)
1817          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1818          * are also counted in. Do not know why?
1819          */
1820         [DTO_XATTR_SET]     = 14,
1821         /**
1822          * credits for inode change during write.
1823          */
1824         [DTO_WRITE_BASE]    = 3,
1825         /**
1826          * credits for single block write.
1827          */
1828         [DTO_WRITE_BLOCK]   = 14,
1829         /**
1830          * Attr set credits for chown.
1831          * This is extra credits for setattr, and it is null without quota
1832          */
1833         [DTO_ATTR_SET_CHOWN] = 0
1834 };
1835
1836 static const struct dt_device_operations osd_dt_ops = {
1837         .dt_root_get       = osd_root_get,
1838         .dt_statfs         = osd_statfs,
1839         .dt_trans_create   = osd_trans_create,
1840         .dt_trans_start    = osd_trans_start,
1841         .dt_trans_stop     = osd_trans_stop,
1842         .dt_trans_cb_add   = osd_trans_cb_add,
1843         .dt_conf_get       = osd_conf_get,
1844         .dt_sync           = osd_sync,
1845         .dt_ro             = osd_ro,
1846         .dt_commit_async   = osd_commit_async,
1847 };
1848
1849 static void osd_object_read_lock(const struct lu_env *env,
1850                                  struct dt_object *dt, unsigned role)
1851 {
1852         struct osd_object *obj = osd_dt_obj(dt);
1853         struct osd_thread_info *oti = osd_oti_get(env);
1854
1855         LINVRNT(osd_invariant(obj));
1856
1857         LASSERT(obj->oo_owner != env);
1858         down_read_nested(&obj->oo_sem, role);
1859
1860         LASSERT(obj->oo_owner == NULL);
1861         oti->oti_r_locks++;
1862 }
1863
1864 static void osd_object_write_lock(const struct lu_env *env,
1865                                   struct dt_object *dt, unsigned role)
1866 {
1867         struct osd_object *obj = osd_dt_obj(dt);
1868         struct osd_thread_info *oti = osd_oti_get(env);
1869
1870         LINVRNT(osd_invariant(obj));
1871
1872         LASSERT(obj->oo_owner != env);
1873         down_write_nested(&obj->oo_sem, role);
1874
1875         LASSERT(obj->oo_owner == NULL);
1876         obj->oo_owner = env;
1877         oti->oti_w_locks++;
1878 }
1879
1880 static void osd_object_read_unlock(const struct lu_env *env,
1881                                    struct dt_object *dt)
1882 {
1883         struct osd_object *obj = osd_dt_obj(dt);
1884         struct osd_thread_info *oti = osd_oti_get(env);
1885
1886         LINVRNT(osd_invariant(obj));
1887
1888         LASSERT(oti->oti_r_locks > 0);
1889         oti->oti_r_locks--;
1890         up_read(&obj->oo_sem);
1891 }
1892
1893 static void osd_object_write_unlock(const struct lu_env *env,
1894                                     struct dt_object *dt)
1895 {
1896         struct osd_object *obj = osd_dt_obj(dt);
1897         struct osd_thread_info *oti = osd_oti_get(env);
1898
1899         LINVRNT(osd_invariant(obj));
1900
1901         LASSERT(obj->oo_owner == env);
1902         LASSERT(oti->oti_w_locks > 0);
1903         oti->oti_w_locks--;
1904         obj->oo_owner = NULL;
1905         up_write(&obj->oo_sem);
1906 }
1907
1908 static int osd_object_write_locked(const struct lu_env *env,
1909                                    struct dt_object *dt)
1910 {
1911         struct osd_object *obj = osd_dt_obj(dt);
1912
1913         LINVRNT(osd_invariant(obj));
1914
1915         return obj->oo_owner == env;
1916 }
1917
1918 static struct timespec *osd_inode_time(const struct lu_env *env,
1919                                        struct inode *inode, __u64 seconds)
1920 {
1921         struct osd_thread_info  *oti = osd_oti_get(env);
1922         struct timespec         *t   = &oti->oti_time;
1923
1924         t->tv_sec = seconds;
1925         t->tv_nsec = 0;
1926         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1927         return t;
1928 }
1929
1930 static void osd_inode_getattr(const struct lu_env *env,
1931                               struct inode *inode, struct lu_attr *attr)
1932 {
1933         attr->la_valid  |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1934                            LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1935                            LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE |
1936                            LA_TYPE;
1937
1938         attr->la_atime   = LTIME_S(inode->i_atime);
1939         attr->la_mtime   = LTIME_S(inode->i_mtime);
1940         attr->la_ctime   = LTIME_S(inode->i_ctime);
1941         attr->la_mode    = inode->i_mode;
1942         attr->la_size    = i_size_read(inode);
1943         attr->la_blocks  = inode->i_blocks;
1944         attr->la_uid     = i_uid_read(inode);
1945         attr->la_gid     = i_gid_read(inode);
1946         attr->la_flags   = ll_inode_to_ext_flags(inode->i_flags);
1947         attr->la_nlink   = inode->i_nlink;
1948         attr->la_rdev    = inode->i_rdev;
1949         attr->la_blksize = 1 << inode->i_blkbits;
1950         attr->la_blkbits = inode->i_blkbits;
1951 }
1952
1953 static int osd_attr_get(const struct lu_env *env,
1954                         struct dt_object *dt,
1955                         struct lu_attr *attr)
1956 {
1957         struct osd_object *obj = osd_dt_obj(dt);
1958
1959         if (unlikely(!dt_object_exists(dt)))
1960                 return -ENOENT;
1961         if (unlikely(obj->oo_destroyed))
1962                 return -ENOENT;
1963
1964         LASSERT(!dt_object_remote(dt));
1965         LINVRNT(osd_invariant(obj));
1966
1967         spin_lock(&obj->oo_guard);
1968         osd_inode_getattr(env, obj->oo_inode, attr);
1969         if (obj->oo_lma_flags & LUSTRE_ORPHAN_FL)
1970                 attr->la_flags |= LUSTRE_ORPHAN_FL;
1971         spin_unlock(&obj->oo_guard);
1972
1973         return 0;
1974 }
1975
1976 static int osd_declare_attr_set(const struct lu_env *env,
1977                                 struct dt_object *dt,
1978                                 const struct lu_attr *attr,
1979                                 struct thandle *handle)
1980 {
1981         struct osd_thandle     *oh;
1982         struct osd_object      *obj;
1983         struct osd_thread_info *info = osd_oti_get(env);
1984         struct lquota_id_info  *qi = &info->oti_qi;
1985         qid_t                   uid;
1986         qid_t                   gid;
1987         long long               bspace;
1988         int                     rc = 0;
1989         bool                    enforce;
1990         ENTRY;
1991
1992         LASSERT(dt != NULL);
1993         LASSERT(handle != NULL);
1994
1995         obj = osd_dt_obj(dt);
1996         LASSERT(osd_invariant(obj));
1997
1998         oh = container_of0(handle, struct osd_thandle, ot_super);
1999         LASSERT(oh->ot_handle == NULL);
2000
2001         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
2002                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2003
2004         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2005                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2006
2007         if (attr == NULL || obj->oo_inode == NULL)
2008                 RETURN(rc);
2009
2010         bspace   = obj->oo_inode->i_blocks;
2011         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
2012         bspace   = toqb(bspace);
2013
2014         /* Changing ownership is always preformed by super user, it should not
2015          * fail with EDQUOT.
2016          *
2017          * We still need to call the osd_declare_qid() to calculate the journal
2018          * credits for updating quota accounting files and to trigger quota
2019          * space adjustment once the operation is completed.*/
2020         if (attr->la_valid & LA_UID || attr->la_valid & LA_GID) {
2021                 /* USERQUOTA */
2022                 uid = i_uid_read(obj->oo_inode);
2023                 qi->lqi_type = USRQUOTA;
2024                 enforce = (attr->la_valid & LA_UID) && (attr->la_uid != uid);
2025                 /* inode accounting */
2026                 qi->lqi_is_blk = false;
2027
2028                 /* one more inode for the new uid ... */
2029                 qi->lqi_id.qid_uid = attr->la_uid;
2030                 qi->lqi_space      = 1;
2031                 /* Reserve credits for the new uid */
2032                 rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2033                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2034                         rc = 0;
2035                 if (rc)
2036                         RETURN(rc);
2037
2038                 /* and one less inode for the current uid */
2039                 qi->lqi_id.qid_uid = uid;
2040                 qi->lqi_space      = -1;
2041                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2042                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2043                         rc = 0;
2044                 if (rc)
2045                         RETURN(rc);
2046
2047                 /* block accounting */
2048                 qi->lqi_is_blk = true;
2049
2050                 /* more blocks for the new uid ... */
2051                 qi->lqi_id.qid_uid = attr->la_uid;
2052                 qi->lqi_space      = bspace;
2053                 /*
2054                  * Credits for the new uid has been reserved, re-use "obj"
2055                  * to save credit reservation.
2056                  */
2057                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2058                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2059                         rc = 0;
2060                 if (rc)
2061                         RETURN(rc);
2062
2063                 /* and finally less blocks for the current uid */
2064                 qi->lqi_id.qid_uid = uid;
2065                 qi->lqi_space      = -bspace;
2066                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2067                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2068                         rc = 0;
2069                 if (rc)
2070                         RETURN(rc);
2071
2072                 /* GROUP QUOTA */
2073                 gid = i_gid_read(obj->oo_inode);
2074                 qi->lqi_type = GRPQUOTA;
2075                 enforce = (attr->la_valid & LA_GID) && (attr->la_gid != gid);
2076
2077                 /* inode accounting */
2078                 qi->lqi_is_blk = false;
2079
2080                 /* one more inode for the new gid ... */
2081                 qi->lqi_id.qid_gid = attr->la_gid;
2082                 qi->lqi_space      = 1;
2083                 rc = osd_declare_qid(env, oh, qi, NULL, enforce, NULL);
2084                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2085                         rc = 0;
2086                 if (rc)
2087                         RETURN(rc);
2088
2089                 /* and one less inode for the current gid */
2090                 qi->lqi_id.qid_gid = gid;
2091                 qi->lqi_space      = -1;
2092                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2093                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2094                         rc = 0;
2095                 if (rc)
2096                         RETURN(rc);
2097
2098                 /* block accounting */
2099                 qi->lqi_is_blk = true;
2100
2101                 /* more blocks for the new gid ... */
2102                 qi->lqi_id.qid_gid = attr->la_gid;
2103                 qi->lqi_space      = bspace;
2104                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2105                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2106                         rc = 0;
2107                 if (rc)
2108                         RETURN(rc);
2109
2110                 /* and finally less blocks for the current gid */
2111                 qi->lqi_id.qid_gid = gid;
2112                 qi->lqi_space      = -bspace;
2113                 rc = osd_declare_qid(env, oh, qi, obj, enforce, NULL);
2114                 if (rc == -EDQUOT || rc == -EINPROGRESS)
2115                         rc = 0;
2116                 if (rc)
2117                         RETURN(rc);
2118         }
2119
2120         RETURN(rc);
2121 }
2122
2123 static int osd_inode_setattr(const struct lu_env *env,
2124                              struct inode *inode, const struct lu_attr *attr)
2125 {
2126         __u64 bits = attr->la_valid;
2127
2128         /* Only allow set size for regular file */
2129         if (!S_ISREG(inode->i_mode))
2130                 bits &= ~(LA_SIZE | LA_BLOCKS);
2131
2132         if (bits == 0)
2133                 return 0;
2134
2135         if (bits & LA_ATIME)
2136                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
2137         if (bits & LA_CTIME)
2138                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
2139         if (bits & LA_MTIME)
2140                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
2141         if (bits & LA_SIZE) {
2142                 LDISKFS_I(inode)->i_disksize = attr->la_size;
2143                 i_size_write(inode, attr->la_size);
2144         }
2145
2146 #if 0
2147         /* OSD should not change "i_blocks" which is used by quota.
2148          * "i_blocks" should be changed by ldiskfs only. */
2149         if (bits & LA_BLOCKS)
2150                 inode->i_blocks = attr->la_blocks;
2151 #endif
2152         if (bits & LA_MODE)
2153                 inode->i_mode = (inode->i_mode & S_IFMT) |
2154                                 (attr->la_mode & ~S_IFMT);
2155         if (bits & LA_UID)
2156                 i_uid_write(inode, attr->la_uid);
2157         if (bits & LA_GID)
2158                 i_gid_write(inode, attr->la_gid);
2159         if (bits & LA_NLINK)
2160                 set_nlink(inode, attr->la_nlink);
2161         if (bits & LA_RDEV)
2162                 inode->i_rdev = attr->la_rdev;
2163
2164         if (bits & LA_FLAGS) {
2165                 /* always keep S_NOCMTIME */
2166                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
2167                                  S_NOCMTIME;
2168         }
2169         return 0;
2170 }
2171
2172 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
2173 {
2174         if ((attr->la_valid & LA_UID && attr->la_uid != i_uid_read(inode)) ||
2175             (attr->la_valid & LA_GID && attr->la_gid != i_gid_read(inode))) {
2176                 struct iattr    iattr;
2177                 int             rc;
2178
2179                 ll_vfs_dq_init(inode);
2180                 iattr.ia_valid = 0;
2181                 if (attr->la_valid & LA_UID)
2182                         iattr.ia_valid |= ATTR_UID;
2183                 if (attr->la_valid & LA_GID)
2184                         iattr.ia_valid |= ATTR_GID;
2185                 iattr.ia_uid = make_kuid(&init_user_ns, attr->la_uid);
2186                 iattr.ia_gid = make_kgid(&init_user_ns, attr->la_gid);
2187
2188                 rc = ll_vfs_dq_transfer(inode, &iattr);
2189                 if (rc) {
2190                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
2191                                "enforcement enabled on the ldiskfs "
2192                                "filesystem?\n", inode->i_sb->s_id, rc);
2193                         return rc;
2194                 }
2195         }
2196         return 0;
2197 }
2198
2199 static int osd_attr_set(const struct lu_env *env,
2200                         struct dt_object *dt,
2201                         const struct lu_attr *attr,
2202                         struct thandle *handle)
2203 {
2204         struct osd_object *obj = osd_dt_obj(dt);
2205         struct inode      *inode;
2206         int rc;
2207
2208         if (!dt_object_exists(dt))
2209                 return -ENOENT;
2210
2211         LASSERT(handle != NULL);
2212         LASSERT(!dt_object_remote(dt));
2213         LASSERT(osd_invariant(obj));
2214
2215         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
2216
2217         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
2218                 struct osd_thread_info  *oti  = osd_oti_get(env);
2219                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
2220                 struct lu_fid           *fid1 = &oti->oti_fid;
2221                 struct osd_inode_id     *id   = &oti->oti_id;
2222                 struct iam_path_descr   *ipd;
2223                 struct iam_container    *bag;
2224                 struct osd_thandle      *oh;
2225                 int                      rc;
2226
2227                 fid_cpu_to_be(fid1, fid0);
2228                 memset(id, 1, sizeof(*id));
2229                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
2230                                   fid0)->oi_dir.od_container;
2231                 ipd = osd_idx_ipd_get(env, bag);
2232                 if (unlikely(ipd == NULL))
2233                         RETURN(-ENOMEM);
2234
2235                 oh = container_of0(handle, struct osd_thandle, ot_super);
2236                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
2237                                 (const struct iam_rec *)id, ipd);
2238                 osd_ipd_put(env, bag, ipd);
2239                 return(rc > 0 ? 0 : rc);
2240         }
2241
2242         inode = obj->oo_inode;
2243
2244         rc = osd_quota_transfer(inode, attr);
2245         if (rc)
2246                 return rc;
2247
2248         spin_lock(&obj->oo_guard);
2249         rc = osd_inode_setattr(env, inode, attr);
2250         spin_unlock(&obj->oo_guard);
2251         if (rc != 0)
2252                 GOTO(out, rc);
2253
2254         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2255
2256         if (!(attr->la_valid & LA_FLAGS))
2257                 GOTO(out, rc);
2258
2259         /* Let's check if there are extra flags need to be set into LMA */
2260         if (attr->la_flags & LUSTRE_LMA_FL_MASKS) {
2261                 struct osd_thread_info *info = osd_oti_get(env);
2262                 struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2263
2264                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
2265                 if (rc != 0)
2266                         GOTO(out, rc);
2267
2268                 lma->lma_incompat |=
2269                         lustre_to_lma_flags(attr->la_flags);
2270                 lustre_lma_swab(lma);
2271                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA,
2272                                      lma, sizeof(*lma), XATTR_REPLACE);
2273                 if (rc != 0) {
2274                         struct osd_device *osd = osd_obj2dev(obj);
2275
2276                         CWARN("%s: set "DFID" lma flags %u failed: rc = %d\n",
2277                               osd_name(osd), PFID(lu_object_fid(&dt->do_lu)),
2278                               lma->lma_incompat, rc);
2279                 } else {
2280                         obj->oo_lma_flags =
2281                                 attr->la_flags & LUSTRE_LMA_FL_MASKS;
2282                 }
2283                 osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
2284         }
2285 out:
2286         osd_trans_exec_check(env, handle, OSD_OT_ATTR_SET);
2287
2288         return rc;
2289 }
2290
2291 static struct dentry *osd_child_dentry_get(const struct lu_env *env,
2292                                            struct osd_object *obj,
2293                                            const char *name, const int namelen)
2294 {
2295         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
2296 }
2297
2298 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
2299                       umode_t mode, struct dt_allocation_hint *hint,
2300                       struct thandle *th)
2301 {
2302         int result;
2303         struct osd_device  *osd = osd_obj2dev(obj);
2304         struct osd_thandle *oth;
2305         struct dt_object   *parent = NULL;
2306         struct inode       *inode;
2307
2308         LINVRNT(osd_invariant(obj));
2309         LASSERT(obj->oo_inode == NULL);
2310         LASSERT(obj->oo_hl_head == NULL);
2311
2312         if (S_ISDIR(mode) && ldiskfs_pdo) {
2313                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
2314                 if (obj->oo_hl_head == NULL)
2315                         return -ENOMEM;
2316         }
2317
2318         oth = container_of(th, struct osd_thandle, ot_super);
2319         LASSERT(oth->ot_handle->h_transaction != NULL);
2320
2321         if (hint != NULL && hint->dah_parent != NULL &&
2322             !dt_object_remote(hint->dah_parent))
2323                 parent = hint->dah_parent;
2324
2325         inode = ldiskfs_create_inode(oth->ot_handle,
2326                                      parent ? osd_dt_obj(parent)->oo_inode :
2327                                               osd_sb(osd)->s_root->d_inode,
2328                                      mode);
2329         if (!IS_ERR(inode)) {
2330                 /* Do not update file c/mtime in ldiskfs. */
2331                 inode->i_flags |= S_NOCMTIME;
2332
2333                 /* For new created object, it must be consistent,
2334                  * and it is unnecessary to scrub against it. */
2335                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
2336
2337                 obj->oo_inode = inode;
2338                 result = 0;
2339         } else {
2340                 if (obj->oo_hl_head != NULL) {
2341                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
2342                         obj->oo_hl_head = NULL;
2343                 }
2344                 result = PTR_ERR(inode);
2345         }
2346         LINVRNT(osd_invariant(obj));
2347         return result;
2348 }
2349
2350 enum {
2351         OSD_NAME_LEN = 255
2352 };
2353
2354 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
2355                      struct lu_attr *attr,
2356                      struct dt_allocation_hint *hint,
2357                      struct dt_object_format *dof,
2358                      struct thandle *th)
2359 {
2360         int result;
2361         struct osd_thandle *oth;
2362         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
2363
2364         LASSERT(S_ISDIR(attr->la_mode));
2365
2366         oth = container_of(th, struct osd_thandle, ot_super);
2367         LASSERT(oth->ot_handle->h_transaction != NULL);
2368         result = osd_mkfile(info, obj, mode, hint, th);
2369
2370         return result;
2371 }
2372
2373 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
2374                         struct lu_attr *attr,
2375                         struct dt_allocation_hint *hint,
2376                         struct dt_object_format *dof,
2377                         struct thandle *th)
2378 {
2379         int result;
2380         struct osd_thandle *oth;
2381         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
2382
2383         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
2384
2385         LASSERT(S_ISREG(attr->la_mode));
2386
2387         oth = container_of(th, struct osd_thandle, ot_super);
2388         LASSERT(oth->ot_handle->h_transaction != NULL);
2389
2390         result = osd_mkfile(info, obj, mode, hint, th);
2391         if (result == 0) {
2392                 LASSERT(obj->oo_inode != NULL);
2393                 if (feat->dif_flags & DT_IND_VARKEY)
2394                         result = iam_lvar_create(obj->oo_inode,
2395                                                  feat->dif_keysize_max,
2396                                                  feat->dif_ptrsize,
2397                                                  feat->dif_recsize_max,
2398                                                  oth->ot_handle);
2399                 else
2400                         result = iam_lfix_create(obj->oo_inode,
2401                                                  feat->dif_keysize_max,
2402                                                  feat->dif_ptrsize,
2403                                                  feat->dif_recsize_max,
2404                                                  oth->ot_handle);
2405
2406         }
2407         return result;
2408 }
2409
2410 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
2411                      struct lu_attr *attr,
2412                      struct dt_allocation_hint *hint,
2413                      struct dt_object_format *dof,
2414                      struct thandle *th)
2415 {
2416         LASSERT(S_ISREG(attr->la_mode));
2417         return osd_mkfile(info, obj, (attr->la_mode &
2418                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2419 }
2420
2421 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
2422                      struct lu_attr *attr,
2423                      struct dt_allocation_hint *hint,
2424                      struct dt_object_format *dof,
2425                      struct thandle *th)
2426 {
2427         LASSERT(S_ISLNK(attr->la_mode));
2428         return osd_mkfile(info, obj, (attr->la_mode &
2429                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
2430 }
2431
2432 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
2433                      struct lu_attr *attr,
2434                      struct dt_allocation_hint *hint,
2435                      struct dt_object_format *dof,
2436                      struct thandle *th)
2437 {
2438         umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
2439         int result;
2440
2441         LINVRNT(osd_invariant(obj));
2442         LASSERT(obj->oo_inode == NULL);
2443         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
2444                 S_ISFIFO(mode) || S_ISSOCK(mode));
2445
2446         result = osd_mkfile(info, obj, mode, hint, th);
2447         if (result == 0) {
2448                 LASSERT(obj->oo_inode != NULL);
2449                 /*
2450                  * This inode should be marked dirty for i_rdev.  Currently
2451                  * that is done in the osd_attr_init().
2452                  */
2453                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
2454                                    attr->la_rdev);
2455         }
2456         LINVRNT(osd_invariant(obj));
2457         return result;
2458 }
2459
2460 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
2461                               struct lu_attr *,
2462                               struct dt_allocation_hint *hint,
2463                               struct dt_object_format *dof,
2464                               struct thandle *);
2465
2466 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
2467 {
2468         osd_obj_type_f result;
2469
2470         switch (type) {
2471         case DFT_DIR:
2472                 result = osd_mkdir;
2473                 break;
2474         case DFT_REGULAR:
2475                 result = osd_mkreg;
2476                 break;
2477         case DFT_SYM:
2478                 result = osd_mksym;
2479                 break;
2480         case DFT_NODE:
2481                 result = osd_mknod;
2482                 break;
2483         case DFT_INDEX:
2484                 result = osd_mk_index;
2485                 break;
2486
2487         default:
2488                 LBUG();
2489                 break;
2490         }
2491         return result;
2492 }
2493
2494
2495 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
2496                         struct dt_object *parent, struct dt_object *child,
2497                         umode_t child_mode)
2498 {
2499         LASSERT(ah);
2500
2501         ah->dah_parent = parent;
2502         ah->dah_mode = child_mode;
2503
2504         if (parent != NULL && !dt_object_remote(parent)) {
2505                 /* will help to find FID->ino at dt_insert("..") */
2506                 struct osd_object *pobj = osd_dt_obj(parent);
2507                 osd_idc_find_and_init(env, osd_obj2dev(pobj), pobj);
2508         }
2509 }
2510
2511 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2512                           struct lu_attr *attr, struct dt_object_format *dof)
2513 {
2514         struct inode   *inode = obj->oo_inode;
2515         __u64           valid = attr->la_valid;
2516         int             result;
2517
2518         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2519
2520         if (dof->dof_type != DFT_NODE)
2521                 attr->la_valid &= ~LA_RDEV;
2522         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2523                 attr->la_valid &= ~LA_ATIME;
2524         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2525                 attr->la_valid &= ~LA_CTIME;
2526         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2527                 attr->la_valid &= ~LA_MTIME;
2528
2529         result = osd_quota_transfer(inode, attr);
2530         if (result)
2531                 return;
2532
2533         if (attr->la_valid != 0) {
2534                 result = osd_inode_setattr(info->oti_env, inode, attr);
2535                 /*
2536                  * The osd_inode_setattr() should always succeed here.  The
2537                  * only error that could be returned is EDQUOT when we are
2538                  * trying to change the UID or GID of the inode. However, this
2539                  * should not happen since quota enforcement is no longer
2540                  * enabled on ldiskfs (lquota takes care of it).
2541                  */
2542                 LASSERTF(result == 0, "%d\n", result);
2543                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2544         }
2545
2546         attr->la_valid = valid;
2547 }
2548
2549 /**
2550  * Helper function for osd_object_create()
2551  *
2552  * \retval 0, on success
2553  */
2554 static int __osd_object_create(struct osd_thread_info *info,
2555                                struct osd_object *obj, struct lu_attr *attr,
2556                                struct dt_allocation_hint *hint,
2557                                struct dt_object_format *dof,
2558                                struct thandle *th)
2559 {
2560         int     result;
2561         __u32   umask;
2562
2563         osd_trans_exec_op(info->oti_env, th, OSD_OT_CREATE);
2564
2565         /* we drop umask so that permissions we pass are not affected */
2566         umask = current->fs->umask;
2567         current->fs->umask = 0;
2568
2569         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2570                                                   th);
2571         if (likely(obj->oo_inode != NULL)) {
2572                 LASSERT(obj->oo_inode->i_state & I_NEW);
2573
2574                 /* Unlock the inode before attr initialization to avoid
2575                  * unnecessary dqget operations. LU-6378 */
2576                 unlock_new_inode(obj->oo_inode);
2577         }
2578
2579         if (likely(result == 0)) {
2580                 osd_attr_init(info, obj, attr, dof);
2581                 osd_object_init0(obj);
2582         }
2583
2584         /* restore previous umask value */
2585         current->fs->umask = umask;
2586
2587         osd_trans_exec_check(info->oti_env, th, OSD_OT_CREATE);
2588
2589         return result;
2590 }
2591
2592 /**
2593  * Helper function for osd_object_create()
2594  *
2595  * \retval 0, on success
2596  */
2597 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2598                            const struct lu_fid *fid, struct thandle *th)
2599 {
2600         struct osd_thread_info *info = osd_oti_get(env);
2601         struct osd_inode_id    *id   = &info->oti_id;
2602         struct osd_device      *osd  = osd_obj2dev(obj);
2603         struct osd_thandle     *oh;
2604         int                     rc;
2605
2606         LASSERT(obj->oo_inode != NULL);
2607
2608         oh = container_of0(th, struct osd_thandle, ot_super);
2609         LASSERT(oh->ot_handle);
2610         osd_trans_exec_op(env, th, OSD_OT_INSERT);
2611
2612         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2613         rc = osd_oi_insert(info, osd, fid, id, oh->ot_handle, OI_CHECK_FLD);
2614         osd_trans_exec_check(env, th, OSD_OT_INSERT);
2615
2616         return rc;
2617 }
2618
2619 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2620                    u64 seq, struct lu_seq_range *range)
2621 {
2622         struct seq_server_site  *ss = osd_seq_site(osd);
2623
2624         if (fid_seq_is_idif(seq)) {
2625                 fld_range_set_ost(range);
2626                 range->lsr_index = idif_ost_idx(seq);
2627                 return 0;
2628         }
2629
2630         if (!fid_seq_in_fldb(seq)) {
2631                 fld_range_set_mdt(range);
2632                 if (ss != NULL)
2633                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2634                          * at all */
2635                         range->lsr_index = ss->ss_node_id;
2636                 return 0;
2637         }
2638
2639         LASSERT(ss != NULL);
2640         fld_range_set_any(range);
2641         /* OSD will only do local fld lookup */
2642         return fld_local_lookup(env, ss->ss_server_fld, seq, range);
2643 }
2644
2645 /*
2646  * Concurrency: no external locking is necessary.
2647  */
2648 static int osd_declare_object_create(const struct lu_env *env,
2649                                      struct dt_object *dt,
2650                                      struct lu_attr *attr,
2651                                      struct dt_allocation_hint *hint,
2652                                      struct dt_object_format *dof,
2653                                      struct thandle *handle)
2654 {
2655         struct osd_thandle      *oh;
2656         int                      rc;
2657         ENTRY;
2658
2659         LASSERT(handle != NULL);
2660
2661         oh = container_of0(handle, struct osd_thandle, ot_super);
2662         LASSERT(oh->ot_handle == NULL);
2663
2664         /* EA object consumes more credits than regular object: osd_mk_index
2665          * vs. osd_mkreg: osd_mk_index will create 2 blocks for root_node and
2666          * leaf_node, could involves the block, block bitmap, groups, GDT
2667          * change for each block, so add 4 * 2 credits in that case. */
2668         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2669                              osd_dto_credits_noquota[DTO_OBJECT_CREATE] +
2670                              (dof->dof_type == DFT_INDEX) ? 4 * 2 : 0);
2671         /* Reuse idle OI block may cause additional one OI block
2672          * to be changed. */
2673         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2674                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2675
2676         if (!attr)
2677                 RETURN(0);
2678
2679         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2680                                    osd_dt_obj(dt), false, NULL, false);
2681         if (rc != 0)
2682                 RETURN(rc);
2683
2684         /* will help to find FID->ino mapping at dt_insert() */
2685         rc = osd_idc_find_and_init(env, osd_obj2dev(osd_dt_obj(dt)),
2686                                    osd_dt_obj(dt));
2687
2688         RETURN(rc);
2689 }
2690
2691 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2692                              struct lu_attr *attr,
2693                              struct dt_allocation_hint *hint,
2694                              struct dt_object_format *dof, struct thandle *th)
2695 {
2696         const struct lu_fid     *fid    = lu_object_fid(&dt->do_lu);
2697         struct osd_object       *obj    = osd_dt_obj(dt);
2698         struct osd_thread_info  *info   = osd_oti_get(env);
2699         int result;
2700         ENTRY;
2701
2702         if (dt_object_exists(dt))
2703                 return -EEXIST;
2704
2705         LINVRNT(osd_invariant(obj));
2706         LASSERT(!dt_object_remote(dt));
2707         LASSERT(osd_write_locked(env, obj));
2708         LASSERT(th != NULL);
2709
2710         if (unlikely(fid_is_acct(fid)))
2711                 /* Quota files can't be created from the kernel any more,
2712                  * 'tune2fs -O quota' will take care of creating them */
2713                 RETURN(-EPERM);
2714
2715         result = __osd_object_create(info, obj, attr, hint, dof, th);
2716         if (result == 0) {
2717                 result = __osd_oi_insert(env, obj, fid, th);
2718                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
2719                         obj->oo_dt.do_body_ops = &osd_body_ops;
2720         }
2721         LASSERT(ergo(result == 0,
2722                 dt_object_exists(dt) && !dt_object_remote(dt)));
2723
2724         LASSERT(osd_invariant(obj));
2725         RETURN(result);
2726 }
2727
2728 /**
2729  * Called to destroy on-disk representation of the object
2730  *
2731  * Concurrency: must be locked
2732  */
2733 static int osd_declare_object_destroy(const struct lu_env *env,
2734                                       struct dt_object *dt,
2735                                       struct thandle *th)
2736 {
2737         struct osd_object  *obj = osd_dt_obj(dt);
2738         struct inode       *inode = obj->oo_inode;
2739         struct osd_thandle *oh;
2740         int                 rc;
2741         ENTRY;
2742
2743         if (inode == NULL)
2744                 RETURN(-ENOENT);
2745
2746         oh = container_of0(th, struct osd_thandle, ot_super);
2747         LASSERT(oh->ot_handle == NULL);
2748
2749         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2750                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2751         /* Recycle idle OI leaf may cause additional three OI blocks
2752          * to be changed. */
2753         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2754                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2755         /* one less inode */
2756         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2757                                    -1, oh, obj, false, NULL, false);
2758         if (rc)
2759                 RETURN(rc);
2760         /* data to be truncated */
2761         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
2762                                    0, oh, obj, true, NULL, false);
2763         if (rc)
2764                 RETURN(rc);
2765
2766         /* will help to find FID->ino when this object is being
2767          * added to PENDING/ */
2768         rc = osd_idc_find_and_init(env, osd_obj2dev(obj), obj);
2769
2770         RETURN(rc);
2771 }
2772
2773 static int osd_object_destroy(const struct lu_env *env,
2774                               struct dt_object *dt,
2775                               struct thandle *th)
2776 {
2777         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2778         struct osd_object      *obj = osd_dt_obj(dt);
2779         struct inode           *inode = obj->oo_inode;
2780         struct osd_device      *osd = osd_obj2dev(obj);
2781         struct osd_thandle     *oh;
2782         int                     result;
2783         ENTRY;
2784
2785         oh = container_of0(th, struct osd_thandle, ot_super);
2786         LASSERT(oh->ot_handle);
2787         LASSERT(inode);
2788         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2789
2790         if (unlikely(fid_is_acct(fid)))
2791                 RETURN(-EPERM);
2792
2793         if (S_ISDIR(inode->i_mode)) {
2794                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1 ||
2795                         inode->i_nlink == 2);
2796                 /* it will check/delete the inode from remote parent,
2797                  * how to optimize it? unlink performance impaction XXX */
2798                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2799                 if (result != 0 && result != -ENOENT) {
2800                         CERROR("%s: delete inode "DFID": rc = %d\n",
2801                                osd_name(osd), PFID(fid), result);
2802                 }
2803                 spin_lock(&obj->oo_guard);
2804                 clear_nlink(inode);
2805                 spin_unlock(&obj->oo_guard);
2806                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2807         }
2808
2809         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2810
2811         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_DESTROY);
2812         result = osd_oi_delete(osd_oti_get(env), osd, fid, oh->ot_handle,
2813                                OI_CHECK_FLD);
2814
2815         osd_trans_exec_check(env, th, OSD_OT_DESTROY);
2816         /* XXX: add to ext3 orphan list */
2817         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2818
2819         /* not needed in the cache anymore */
2820         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2821         obj->oo_destroyed = 1;
2822
2823         RETURN(0);
2824 }
2825
2826 /**
2827  * Put the fid into lustre_mdt_attrs, and then place the structure
2828  * inode's ea. This fid should not be altered during the life time
2829  * of the inode.
2830  *
2831  * \retval +ve, on success
2832  * \retval -ve, on error
2833  *
2834  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2835  */
2836 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2837                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
2838 {
2839         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2840         int                      rc;
2841         ENTRY;
2842
2843         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2844                 RETURN(0);
2845
2846         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_OST_EA_FID_SET))
2847                 rc = -ENOMEM;
2848
2849         lustre_lma_init(lma, fid, compat, incompat);
2850         lustre_lma_swab(lma);
2851
2852         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2853                              XATTR_CREATE);
2854         /* LMA may already exist, but we need to check that all the
2855          * desired compat/incompat flags have been added. */
2856         if (unlikely(rc == -EEXIST)) {
2857                 if (compat == 0 && incompat == 0)
2858                         RETURN(0);
2859
2860                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
2861                                      XATTR_NAME_LMA, info->oti_mdt_attrs_old,
2862                                      LMA_OLD_SIZE);
2863                 if (rc <= 0)
2864                         RETURN(-EINVAL);
2865
2866                 lustre_lma_swab(lma);
2867                 if (!(~lma->lma_compat & compat) &&
2868                     !(~lma->lma_incompat & incompat))
2869                         RETURN(0);
2870
2871                 lma->lma_compat |= compat;
2872                 lma->lma_incompat |= incompat;
2873                 lustre_lma_swab(lma);
2874                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
2875                                      sizeof(*lma), XATTR_REPLACE);
2876         }
2877
2878         RETURN(rc);
2879 }
2880
2881 /**
2882  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2883  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2884  * To have compatilibility with 1.8 ldiskfs driver we need to have
2885  * magic number at start of fid data.
2886  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2887  * its inmemory API.
2888  */
2889 static void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2890                                          const struct lu_fid *fid)
2891 {
2892         if (!fid_is_namespace_visible(fid) ||
2893             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2894                 param->edp_magic = 0;
2895                 return;
2896         }
2897
2898         param->edp_magic = LDISKFS_LUFID_MAGIC;
2899         param->edp_len =  sizeof(struct lu_fid) + 1;
2900         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2901 }
2902
2903 /**
2904  * Try to read the fid from inode ea into dt_rec.
2905  *
2906  * \param fid object fid.
2907  *
2908  * \retval 0 on success
2909  */
2910 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2911                           __u32 ino, struct lu_fid *fid,
2912                           struct osd_inode_id *id)
2913 {
2914         struct osd_thread_info *info  = osd_oti_get(env);
2915         struct inode           *inode;
2916         ENTRY;
2917
2918         osd_id_gen(id, ino, OSD_OII_NOGEN);
2919         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2920         if (IS_ERR(inode))
2921                 RETURN(PTR_ERR(inode));
2922
2923         iput(inode);
2924         RETURN(0);
2925 }
2926
2927 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2928                                         struct inode *dir,
2929                                         struct inode *parent_dir,
2930                                         const struct lu_fid *dot_fid,
2931                                         const struct lu_fid *dot_dot_fid,
2932                                         struct osd_thandle *oth)
2933 {
2934         struct ldiskfs_dentry_param *dot_ldp;
2935         struct ldiskfs_dentry_param *dot_dot_ldp;
2936         __u32 saved_nlink = dir->i_nlink;
2937         int rc;
2938
2939         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2940         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2941
2942         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2943         dot_ldp->edp_magic = 0;
2944
2945         rc = ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2946                                     dir, dot_ldp, dot_dot_ldp);
2947         /* The ldiskfs_add_dot_dotdot() may dir->i_nlink as 2, then
2948          * the subseqent ref_add() will increase the dir->i_nlink
2949          * as 3. That is incorrect for new created directory.
2950          *
2951          * It looks like hack, because we want to make the OSD API
2952          * to be order-independent for new created directory object
2953          * between dt_insert(..) and ref_add() operations.
2954          *
2955          * Here, we only restore the in-RAM dir-inode's nlink attr,
2956          * becuase if the nlink attr is not 2, then there will be
2957          * ref_add() called following the dt_insert(..), such call
2958          * will make both the in-RAM and on-disk dir-inode's nlink
2959          * attr to be set as 2. LU-7447 */
2960         set_nlink(dir, saved_nlink);
2961         return rc;
2962 }
2963
2964 /**
2965  * Create an local agent inode for remote entry
2966  */
2967 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2968                                                   struct osd_device *osd,
2969                                                   struct osd_object *pobj,
2970                                                   const struct lu_fid *fid,
2971                                                   __u32 type,
2972                                                   struct thandle *th)
2973 {
2974         struct osd_thread_info  *info = osd_oti_get(env);
2975         struct inode            *local;
2976         struct osd_thandle      *oh;
2977         int                     rc;
2978         ENTRY;
2979
2980         LASSERT(th);
2981         oh = container_of(th, struct osd_thandle, ot_super);
2982         LASSERT(oh->ot_handle->h_transaction != NULL);
2983
2984         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, type);
2985         if (IS_ERR(local)) {
2986                 CERROR("%s: create local error %d\n", osd_name(osd),
2987                        (int)PTR_ERR(local));
2988                 RETURN(local);
2989         }
2990
2991         ldiskfs_set_inode_state(local, LDISKFS_STATE_LUSTRE_NOSCRUB);
2992         unlock_new_inode(local);
2993
2994         /* Set special LMA flag for local agent inode */
2995         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
2996         if (rc != 0) {
2997                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2998                        osd_name(osd), PFID(fid), rc);
2999                 RETURN(ERR_PTR(rc));
3000         }
3001
3002         if (!S_ISDIR(type))
3003                 RETURN(local);
3004
3005         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
3006                                          lu_object_fid(&pobj->oo_dt.do_lu),
3007                                          fid, oh);
3008         if (rc != 0) {
3009                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
3010                         osd_name(osd), PFID(fid), rc);
3011                 RETURN(ERR_PTR(rc));
3012         }
3013
3014         RETURN(local);
3015 }
3016
3017 /**
3018  * when direntry is deleted, we have to take care of possible agent inode
3019  * referenced by that. unfortunately we can't do this at that point:
3020  * iget() within a running transaction leads to deadlock and we better do
3021  * not call that every delete declaration to save performance. so we put
3022  * a potention agent inode on a list and process that once the transaction
3023  * is over. Notice it's not any worse in terms of real orphans as regular
3024  * object destroy doesn't put inodes on the on-disk orphan list. this should
3025  * be addressed separately
3026  */
3027 static int osd_schedule_agent_inode_removal(const struct lu_env *env,
3028                                             struct osd_thandle *oh,
3029                                             __u32 ino)
3030 {
3031         struct osd_device      *osd = osd_dt_dev(oh->ot_super.th_dev);
3032         struct osd_obj_orphan *oor;
3033
3034         OBD_ALLOC_PTR(oor);
3035         if (oor == NULL)
3036                 return -ENOMEM;
3037
3038         oor->oor_ino = ino;
3039         oor->oor_env = (struct lu_env *)env;
3040         spin_lock(&osd->od_osfs_lock);
3041         list_add(&oor->oor_list, &osd->od_orphan_list);
3042         spin_unlock(&osd->od_osfs_lock);
3043
3044         oh->ot_remove_agents = 1;
3045
3046         return 0;
3047
3048 }
3049
3050 static int osd_process_scheduled_agent_removals(const struct lu_env *env,
3051                                                 struct osd_device *osd)
3052 {
3053         struct osd_thread_info *info = osd_oti_get(env);
3054         struct osd_obj_orphan *oor, *tmp;
3055         struct osd_inode_id id;
3056         struct list_head list;
3057         struct inode *inode;
3058         struct lu_fid fid;
3059         handle_t *jh;
3060         __u32 ino;
3061
3062         INIT_LIST_HEAD(&list);
3063
3064         spin_lock(&osd->od_osfs_lock);
3065         list_for_each_entry_safe(oor, tmp, &osd->od_orphan_list, oor_list) {
3066                 if (oor->oor_env == env) {
3067                         list_del(&oor->oor_list);
3068                         list_add(&oor->oor_list, &list);
3069                 }
3070         }
3071         spin_unlock(&osd->od_osfs_lock);
3072
3073         list_for_each_entry_safe(oor, tmp, &list, oor_list) {
3074
3075                 ino = oor->oor_ino;
3076
3077                 list_del(&oor->oor_list);
3078                 OBD_FREE_PTR(oor);
3079
3080                 osd_id_gen(&id, ino, OSD_OII_NOGEN);
3081                 inode = osd_iget_fid(info, osd, &id, &fid);
3082                 if (IS_ERR(inode))
3083                         continue;
3084
3085                 if (!osd_remote_fid(env, osd, &fid)) {
3086                         iput(inode);
3087                         continue;
3088                 }
3089
3090                 jh = osd_journal_start_sb(osd_sb(osd), LDISKFS_HT_MISC, 1);
3091                 clear_nlink(inode);
3092                 mark_inode_dirty(inode);
3093                 ldiskfs_journal_stop(jh);
3094                 iput(inode);
3095         }
3096
3097         return 0;
3098 }
3099
3100 /**
3101  * OSD layer object create function for interoperability mode (b11826).
3102  * This is mostly similar to osd_object_create(). Only difference being, fid is
3103  * inserted into inode ea here.
3104  *
3105  * \retval   0, on success
3106  * \retval -ve, on error
3107  */
3108 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
3109                                 struct lu_attr *attr,
3110                                 struct dt_allocation_hint *hint,
3111                                 struct dt_object_format *dof,
3112                                 struct thandle *th)
3113 {
3114         const struct lu_fid     *fid    = lu_object_fid(&dt->do_lu);
3115         struct osd_object       *obj    = osd_dt_obj(dt);
3116         struct osd_thread_info  *info   = osd_oti_get(env);
3117         int                      result, on_ost = 0;
3118
3119         ENTRY;
3120
3121         if (dt_object_exists(dt))
3122                 RETURN(-EEXIST);
3123
3124         LASSERT(osd_invariant(obj));
3125         LASSERT(!dt_object_remote(dt));
3126         LASSERT(osd_write_locked(env, obj));
3127         LASSERT(th != NULL);
3128
3129         if (unlikely(fid_is_acct(fid)))
3130                 /* Quota files can't be created from the kernel any more,
3131                  * 'tune2fs -O quota' will take care of creating them */
3132                 RETURN(-EPERM);
3133
3134         result = __osd_object_create(info, obj, attr, hint, dof, th);
3135         if (result == 0) {
3136                 if (fid_is_idif(fid) &&
3137                     !osd_dev(dt->do_lu.lo_dev)->od_index_in_idif) {
3138                         struct lu_fid *tfid = &info->oti_fid;
3139                         struct ost_id *oi   = &info->oti_ostid;
3140
3141                         fid_to_ostid(fid, oi);
3142                         ostid_to_fid(tfid, oi, 0);
3143                         on_ost = 1;
3144                         result = osd_ea_fid_set(info, obj->oo_inode, tfid,
3145                                                 LMAC_FID_ON_OST, 0);
3146                 } else {
3147                         on_ost = fid_is_on_ost(info, osd_obj2dev(obj),
3148                                                fid, OI_CHECK_FLD);
3149                         result = osd_ea_fid_set(info, obj->oo_inode, fid,
3150                                                 on_ost ? LMAC_FID_ON_OST : 0,
3151                                                 0);
3152                 }
3153                 if (obj->oo_dt.do_body_ops == &osd_body_ops_new)
3154                         obj->oo_dt.do_body_ops = &osd_body_ops;
3155         }
3156
3157         if (result == 0)
3158                 result = __osd_oi_insert(env, obj, fid, th);
3159
3160         /* a small optimization - dt_insert() isn't usually applied
3161          * to OST objects, so we don't need to cache OI mapping for
3162          * OST objects */
3163         if (result == 0 && on_ost == 0) {
3164                 struct osd_device *osd = osd_dev(dt->do_lu.lo_dev);
3165                 result = osd_idc_find_and_init(env, osd, obj);
3166                 LASSERT(result == 0);
3167         }
3168
3169         LASSERT(ergo(result == 0,
3170                      dt_object_exists(dt) && !dt_object_remote(dt)));
3171         LINVRNT(osd_invariant(obj));
3172         RETURN(result);
3173 }
3174
3175 static int osd_declare_object_ref_add(const struct lu_env *env,
3176                                       struct dt_object *dt,
3177                                       struct thandle *handle)
3178 {
3179         struct osd_thandle       *oh;
3180
3181         /* it's possible that object doesn't exist yet */
3182         LASSERT(handle != NULL);
3183
3184         oh = container_of0(handle, struct osd_thandle, ot_super);
3185         LASSERT(oh->ot_handle == NULL);
3186
3187         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
3188                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
3189
3190         return 0;
3191 }
3192
3193 /*
3194  * Concurrency: @dt is write locked.
3195  */
3196 static int osd_object_ref_add(const struct lu_env *env,
3197                               struct dt_object *dt, struct thandle *th)
3198 {
3199         struct osd_object  *obj = osd_dt_obj(dt);
3200         struct inode       *inode = obj->oo_inode;
3201         struct osd_thandle *oh;
3202         int                 rc = 0;
3203
3204         if (!dt_object_exists(dt) || obj->oo_destroyed)
3205                 return -ENOENT;
3206
3207         LINVRNT(osd_invariant(obj));
3208         LASSERT(!dt_object_remote(dt));
3209         LASSERT(osd_write_locked(env, obj));
3210         LASSERT(th != NULL);
3211
3212         oh = container_of0(th, struct osd_thandle, ot_super);
3213         LASSERT(oh->ot_handle != NULL);
3214
3215         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
3216
3217         CDEBUG(D_INODE, DFID" increase nlink %d\n",
3218                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
3219         /*
3220          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
3221          * (65000) subdirectories by storing "1" in i_nlink if the link count
3222          * would otherwise overflow. Directory tranversal tools understand
3223          * that (st_nlink == 1) indicates that the filesystem dose not track
3224          * hard links count on the directory, and will not abort subdirectory
3225          * scanning early once (st_nlink - 2) subdirs have been found.
3226          *
3227          * This also has to properly handle the case of inodes with nlink == 0
3228          * in case they are being linked into the PENDING directory
3229          */
3230         spin_lock(&obj->oo_guard);
3231         if (unlikely(inode->i_nlink == 0))
3232                 /* inc_nlink from 0 may cause WARN_ON */
3233                 set_nlink(inode, 1);
3234         else {
3235                 ldiskfs_inc_count(oh->ot_handle, inode);
3236                 if (!S_ISDIR(inode->i_mode))
3237                         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
3238         }
3239         spin_unlock(&obj->oo_guard);
3240
3241         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3242         LINVRNT(osd_invariant(obj));
3243
3244         osd_trans_exec_check(env, th, OSD_OT_REF_ADD);
3245
3246         return rc;
3247 }
3248
3249 static int osd_declare_object_ref_del(const struct lu_env *env,
3250                                       struct dt_object *dt,
3251                                       struct thandle *handle)
3252 {
3253         struct osd_thandle *oh;
3254
3255         if (!dt_object_exists(dt))
3256                 return -ENOENT;
3257
3258         LASSERT(!dt_object_remote(dt));
3259         LASSERT(handle != NULL);
3260
3261         oh = container_of0(handle, struct osd_thandle, ot_super);
3262         LASSERT(oh->ot_handle == NULL);
3263
3264         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
3265                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
3266
3267         return 0;
3268 }
3269
3270 /*
3271  * Concurrency: @dt is write locked.
3272  */
3273 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
3274                               struct thandle *th)
3275 {
3276         struct osd_object       *obj = osd_dt_obj(dt);
3277         struct inode            *inode = obj->oo_inode;
3278         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
3279         struct osd_thandle      *oh;
3280
3281         if (!dt_object_exists(dt))
3282                 return -ENOENT;
3283
3284         LINVRNT(osd_invariant(obj));
3285         LASSERT(!dt_object_remote(dt));
3286         LASSERT(osd_write_locked(env, obj));
3287         LASSERT(th != NULL);
3288
3289         oh = container_of0(th, struct osd_thandle, ot_super);
3290         LASSERT(oh->ot_handle != NULL);
3291
3292         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
3293
3294         spin_lock(&obj->oo_guard);
3295         /* That can be result of upgrade from old Lustre version and
3296          * applied only to local files.  Just skip this ref_del call.
3297          * ext4_unlink() only treats this as a warning, don't LASSERT here.*/
3298         if (inode->i_nlink == 0) {
3299                 CDEBUG_LIMIT(fid_is_norm(lu_object_fid(&dt->do_lu)) ?
3300                              D_ERROR : D_INODE, "%s: nlink == 0 on "DFID
3301                              ", maybe an upgraded file? (LU-3915)\n",
3302                              osd_name(osd), PFID(lu_object_fid(&dt->do_lu)));
3303                 spin_unlock(&obj->oo_guard);
3304                 return 0;
3305         }
3306
3307         CDEBUG(D_INODE, DFID" decrease nlink %d\n",
3308                PFID(lu_object_fid(&dt->do_lu)), inode->i_nlink);
3309
3310         ldiskfs_dec_count(oh->ot_handle, inode);
3311         spin_unlock(&obj->oo_guard);
3312
3313         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3314         LINVRNT(osd_invariant(obj));
3315
3316         osd_trans_exec_check(env, th, OSD_OT_REF_DEL);
3317
3318         return 0;
3319 }
3320
3321 /*
3322  * Get the 64-bit version for an inode.
3323  */
3324 static int osd_object_version_get(const struct lu_env *env,
3325                                   struct dt_object *dt, dt_obj_version_t *ver)
3326 {
3327         struct inode *inode = osd_dt_obj(dt)->oo_inode;
3328
3329         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
3330                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
3331         *ver = LDISKFS_I(inode)->i_fs_version;
3332         return 0;
3333 }
3334
3335 /*
3336  * Concurrency: @dt is read locked.
3337  */
3338 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
3339                          struct lu_buf *buf, const char *name)
3340 {
3341         struct osd_object      *obj    = osd_dt_obj(dt);
3342         struct inode           *inode  = obj->oo_inode;
3343         struct osd_thread_info *info   = osd_oti_get(env);
3344         struct dentry          *dentry = &info->oti_obj_dentry;
3345
3346         /* version get is not real XATTR but uses xattr API */
3347         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3348                 /* for version we are just using xattr API but change inode
3349                  * field instead */
3350                 if (buf->lb_len == 0)
3351                         return sizeof(dt_obj_version_t);
3352
3353                 if (buf->lb_len < sizeof(dt_obj_version_t))
3354                         return -ERANGE;
3355
3356                 osd_object_version_get(env, dt, buf->lb_buf);
3357
3358                 return sizeof(dt_obj_version_t);
3359         }
3360
3361         if (!dt_object_exists(dt))
3362                 return -ENOENT;
3363
3364         LASSERT(!dt_object_remote(dt));
3365         LASSERT(inode->i_op != NULL);
3366         LASSERT(inode->i_op->getxattr != NULL);
3367
3368         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
3369 }
3370
3371
3372 static int osd_declare_xattr_set(const struct lu_env *env,
3373                                  struct dt_object *dt,
3374                                  const struct lu_buf *buf, const char *name,
3375                                  int fl, struct thandle *handle)
3376 {
3377         struct osd_thandle *oh;
3378         int credits;
3379         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3380
3381         LASSERT(handle != NULL);
3382
3383         oh = container_of0(handle, struct osd_thandle, ot_super);
3384         LASSERT(oh->ot_handle == NULL);
3385
3386         if (strcmp(name, XATTR_NAME_LMA) == 0) {
3387                 /* For non-upgrading case, the LMA is set first and
3388                  * usually fit inode. But for upgrade case, the LMA
3389                  * may be in another separated EA block. */
3390                 if (!dt_object_exists(dt))
3391                         credits = 0;
3392                 else if (fl == LU_XATTR_REPLACE)
3393                         credits = 1;
3394                 else
3395                         goto upgrade;
3396         } else if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3397                 credits = 1;
3398         } else {
3399 upgrade:
3400                 credits = osd_dto_credits_noquota[DTO_XATTR_SET];
3401
3402                 if (buf != NULL) {
3403                         ssize_t buflen;
3404
3405                         if (buf->lb_buf == NULL && dt_object_exists(dt)) {
3406                                 /* learn xattr size from osd_xattr_get if
3407                                    attribute has not been read yet */
3408                                 buflen = __osd_xattr_get(
3409                                     osd_dt_obj(dt)->oo_inode,
3410                                     &osd_oti_get(env)->oti_obj_dentry,
3411                                     name, NULL, 0);
3412                                 if (buflen < 0)
3413                                         buflen = 0;
3414                         } else {
3415                                 buflen = buf->lb_len;
3416                         }
3417
3418                         if (buflen > sb->s_blocksize) {
3419                                 credits += osd_calc_bkmap_credits(
3420                                     sb, NULL, 0, -1,
3421                                     (buflen + sb->s_blocksize - 1) >>
3422                                     sb->s_blocksize_bits);
3423                         }
3424                 }
3425                 /*
3426                  * xattr set may involve inode quota change, reserve credits for
3427                  * dquot_initialize()
3428                  */
3429                 credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
3430         }
3431
3432         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET, credits);
3433
3434         return 0;
3435 }
3436
3437 /*
3438  * Set the 64-bit version for object
3439  */
3440 static void osd_object_version_set(const struct lu_env *env,
3441                                    struct dt_object *dt,
3442                                    dt_obj_version_t *new_version)
3443 {
3444         struct inode *inode = osd_dt_obj(dt)->oo_inode;
3445
3446         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
3447                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
3448
3449         LDISKFS_I(inode)->i_fs_version = *new_version;
3450         /** Version is set after all inode operations are finished,
3451          *  so we should mark it dirty here */
3452         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
3453 }
3454
3455 /*
3456  * Concurrency: @dt is write locked.
3457  */
3458 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
3459                          const struct lu_buf *buf, const char *name, int fl,
3460                          struct thandle *handle)
3461 {
3462         struct osd_object      *obj      = osd_dt_obj(dt);
3463         struct inode           *inode    = obj->oo_inode;
3464         struct osd_thread_info *info     = osd_oti_get(env);
3465         int                     fs_flags = 0;
3466         int                     rc;
3467         ENTRY;
3468
3469         LASSERT(handle != NULL);
3470
3471         /* version set is not real XATTR */
3472         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
3473                 /* for version we are just using xattr API but change inode
3474                  * field instead */
3475                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
3476                 osd_object_version_set(env, dt, buf->lb_buf);
3477                 return sizeof(dt_obj_version_t);
3478         }
3479
3480         CDEBUG(D_INODE, DFID" set xattr '%s' with size %zu\n",
3481                PFID(lu_object_fid(&dt->do_lu)), name, buf->lb_len);
3482
3483         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3484         if (fl & LU_XATTR_REPLACE)
3485                 fs_flags |= XATTR_REPLACE;
3486
3487         if (fl & LU_XATTR_CREATE)
3488                 fs_flags |= XATTR_CREATE;
3489
3490         if (strcmp(name, XATTR_NAME_LMV) == 0) {
3491                 struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
3492                 int                      rc;
3493
3494                 rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
3495                 if (rc != 0)
3496                         RETURN(rc);
3497
3498                 lma->lma_incompat |= LMAI_STRIPED;
3499                 lustre_lma_swab(lma);
3500                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
3501                                      sizeof(*lma), XATTR_REPLACE);
3502                 if (rc != 0)
3503                         RETURN(rc);
3504         }
3505
3506         if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_LINKEA_OVERFLOW) &&
3507             strcmp(name, XATTR_NAME_LINK) == 0)
3508                 return -ENOSPC;
3509
3510         rc = __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
3511                                fs_flags);
3512         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3513
3514         return rc;
3515 }
3516
3517 /*
3518  * Concurrency: @dt is read locked.
3519  */
3520 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
3521                           const struct lu_buf *buf)
3522 {
3523         struct osd_object      *obj    = osd_dt_obj(dt);
3524         struct inode           *inode  = obj->oo_inode;
3525         struct osd_thread_info *info   = osd_oti_get(env);
3526         struct dentry          *dentry = &info->oti_obj_dentry;
3527
3528         if (!dt_object_exists(dt))
3529                 return -ENOENT;
3530
3531         LASSERT(!dt_object_remote(dt));
3532         LASSERT(inode->i_op != NULL);
3533         LASSERT(inode->i_op->listxattr != NULL);
3534
3535         dentry->d_inode = inode;
3536         dentry->d_sb = inode->i_sb;
3537         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
3538 }
3539
3540 static int osd_declare_xattr_del(const struct lu_env *env,
3541                                  struct dt_object *dt, const char *name,
3542                                  struct thandle *handle)
3543 {
3544         struct osd_thandle *oh;
3545         struct super_block *sb = osd_sb(osd_dev(dt->do_lu.lo_dev));
3546
3547         LASSERT(!dt_object_remote(dt));
3548         LASSERT(handle != NULL);
3549
3550         oh = container_of0(handle, struct osd_thandle, ot_super);
3551         LASSERT(oh->ot_handle == NULL);
3552
3553         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
3554                              osd_dto_credits_noquota[DTO_XATTR_SET]);
3555         /*
3556          * xattr del may involve inode quota change, reserve credits for
3557          * dquot_initialize()
3558          */
3559         oh->ot_credits += LDISKFS_MAXQUOTAS_INIT_BLOCKS(sb);
3560
3561         return 0;
3562 }
3563
3564 /*
3565  * Concurrency: @dt is write locked.
3566  */
3567 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
3568                          const char *name, struct thandle *handle)
3569 {
3570         struct osd_object      *obj    = osd_dt_obj(dt);
3571         struct inode           *inode  = obj->oo_inode;
3572         struct osd_thread_info *info   = osd_oti_get(env);
3573         struct dentry          *dentry = &info->oti_obj_dentry;
3574         int                     rc;
3575
3576         if (!dt_object_exists(dt))
3577                 return -ENOENT;
3578
3579         LASSERT(!dt_object_remote(dt));
3580         LASSERT(inode->i_op != NULL);
3581         LASSERT(inode->i_op->removexattr != NULL);
3582         LASSERT(handle != NULL);
3583
3584         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
3585
3586         ll_vfs_dq_init(inode);
3587         dentry->d_inode = inode;
3588         dentry->d_sb = inode->i_sb;
3589         rc = inode->i_op->removexattr(dentry, name);
3590         osd_trans_exec_check(env, handle, OSD_OT_XATTR_SET);
3591         return rc;
3592 }
3593
3594 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt,
3595                            __u64 start, __u64 end)
3596 {
3597         struct osd_object       *obj    = osd_dt_obj(dt);
3598         struct inode            *inode  = obj->oo_inode;
3599         struct osd_thread_info  *info   = osd_oti_get(env);
3600         struct dentry           *dentry = &info->oti_obj_dentry;
3601         struct file             *file   = &info->oti_file;
3602         int                     rc;
3603
3604         ENTRY;
3605
3606         dentry->d_inode = inode;
3607         dentry->d_sb = inode->i_sb;
3608         file->f_path.dentry = dentry;
3609         file->f_mapping = inode->i_mapping;
3610         file->f_op = inode->i_fop;
3611         set_file_inode(file, inode);
3612
3613         rc = ll_vfs_fsync_range(file, start, end, 0);
3614
3615         RETURN(rc);
3616 }
3617
3618 /*
3619  * Index operations.
3620  */
3621
3622 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3623                            const struct dt_index_features *feat)
3624 {
3625         struct iam_descr *descr;
3626
3627         if (osd_object_is_root(o))
3628                 return feat == &dt_directory_features;
3629
3630         LASSERT(o->oo_dir != NULL);
3631
3632         descr = o->oo_dir->od_container.ic_descr;
3633         if (feat == &dt_directory_features) {
3634                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3635                         return 1;
3636                 else
3637                         return 0;
3638         } else {
3639                 return
3640                         feat->dif_keysize_min <= descr->id_key_size &&
3641                         descr->id_key_size <= feat->dif_keysize_max &&
3642                         feat->dif_recsize_min <= descr->id_rec_size &&
3643                         descr->id_rec_size <= feat->dif_recsize_max &&
3644                         !(feat->dif_flags & (DT_IND_VARKEY |
3645                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3646                         ergo(feat->dif_flags & DT_IND_UPDATE,
3647                              1 /* XXX check that object (and file system) is
3648                                 * writable */);
3649         }
3650 }
3651
3652 static int osd_iam_container_init(const struct lu_env *env,
3653                                   struct osd_object *obj,
3654                                   struct osd_directory *dir)
3655 {
3656         struct iam_container *bag = &dir->od_container;
3657         int result;
3658
3659         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3660         if (result != 0)
3661                 return result;
3662
3663         result = iam_container_setup(bag);
3664         if (result == 0)
3665                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3666         else
3667                 iam_container_fini(bag);
3668
3669         return result;
3670 }
3671
3672
3673 /*
3674  * Concurrency: no external locking is necessary.
3675  */
3676 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3677                          const struct dt_index_features *feat)
3678 {
3679         int                      result;
3680         int                      skip_iam = 0;
3681         struct osd_object       *obj = osd_dt_obj(dt);
3682
3683         LINVRNT(osd_invariant(obj));
3684
3685         if (osd_object_is_root(obj)) {
3686                 dt->do_index_ops = &osd_index_ea_ops;
3687                 result = 0;
3688         } else if (feat == &dt_directory_features) {
3689                 dt->do_index_ops = &osd_index_ea_ops;
3690                 if (obj->oo_inode == NULL || S_ISDIR(obj->oo_inode->i_mode))
3691                         result = 0;
3692                 else
3693                         result = -ENOTDIR;
3694                 skip_iam = 1;
3695         } else if (unlikely(feat == &dt_otable_features)) {
3696                 dt->do_index_ops = &osd_otable_ops;
3697                 return 0;
3698         } else if (unlikely(feat == &dt_acct_features)) {
3699                 dt->do_index_ops = &osd_acct_index_ops;
3700                 result = 0;
3701                 skip_iam = 1;
3702         } else if (!osd_has_index(obj)) {
3703                 struct osd_directory *dir;
3704
3705                 OBD_ALLOC_PTR(dir);
3706                 if (dir != NULL) {
3707
3708                         spin_lock(&obj->oo_guard);
3709                         if (obj->oo_dir == NULL)
3710                                 obj->oo_dir = dir;
3711                         else
3712                                 /*
3713                                  * Concurrent thread allocated container data.
3714                                  */
3715                                 OBD_FREE_PTR(dir);
3716                         spin_unlock(&obj->oo_guard);
3717                         /*
3718                          * Now, that we have container data, serialize its
3719                          * initialization.
3720                          */
3721                         down_write(&obj->oo_ext_idx_sem);
3722                         /*
3723                          * recheck under lock.
3724                          */
3725                         if (!osd_has_index(obj))
3726                                 result = osd_iam_container_init(env, obj,
3727                                                                 obj->oo_dir);
3728                         else
3729                                 result = 0;
3730                         up_write(&obj->oo_ext_idx_sem);
3731                 } else {
3732                         result = -ENOMEM;
3733                 }
3734         } else {
3735                 result = 0;
3736         }
3737
3738         if (result == 0 && skip_iam == 0) {
3739                 if (!osd_iam_index_probe(env, obj, feat))
3740                         result = -ENOTDIR;
3741         }
3742         LINVRNT(osd_invariant(obj));
3743
3744         if (result == 0 && feat == &dt_quota_glb_features &&
3745             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3746                 result = osd_quota_migration(env, dt);
3747
3748         return result;
3749 }
3750
3751 static int osd_otable_it_attr_get(const struct lu_env *env,
3752                                  struct dt_object *dt,
3753                                  struct lu_attr *attr)
3754 {
3755         attr->la_valid = 0;
3756         return 0;
3757 }
3758
3759 static const struct dt_object_operations osd_obj_ops = {
3760         .do_read_lock         = osd_object_read_lock,
3761         .do_write_lock        = osd_object_write_lock,
3762         .do_read_unlock       = osd_object_read_unlock,
3763         .do_write_unlock      = osd_object_write_unlock,
3764         .do_write_locked      = osd_object_write_locked,
3765         .do_attr_get          = osd_attr_get,
3766         .do_declare_attr_set  = osd_declare_attr_set,
3767         .do_attr_set          = osd_attr_set,
3768         .do_ah_init           = osd_ah_init,
3769         .do_declare_create    = osd_declare_object_create,
3770         .do_create            = osd_object_create,
3771         .do_declare_destroy   = osd_declare_object_destroy,
3772         .do_destroy           = osd_object_destroy,
3773         .do_index_try         = osd_index_try,
3774         .do_declare_ref_add   = osd_declare_object_ref_add,
3775         .do_ref_add           = osd_object_ref_add,
3776         .do_declare_ref_del   = osd_declare_object_ref_del,
3777         .do_ref_del           = osd_object_ref_del,
3778         .do_xattr_get         = osd_xattr_get,
3779         .do_declare_xattr_set = osd_declare_xattr_set,
3780         .do_xattr_set         = osd_xattr_set,
3781         .do_declare_xattr_del = osd_declare_xattr_del,
3782         .do_xattr_del         = osd_xattr_del,
3783         .do_xattr_list        = osd_xattr_list,
3784         .do_object_sync       = osd_object_sync,
3785 };
3786
3787 /**
3788  * dt_object_operations for interoperability mode
3789  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3790  */
3791 static const struct dt_object_operations osd_obj_ea_ops = {
3792         .do_read_lock         = osd_object_read_lock,
3793         .do_write_lock        = osd_object_write_lock,
3794         .do_read_unlock       = osd_object_read_unlock,
3795         .do_write_unlock      = osd_object_write_unlock,
3796         .do_write_locked      = osd_object_write_locked,
3797         .do_attr_get          = osd_attr_get,
3798         .do_declare_attr_set  = osd_declare_attr_set,
3799         .do_attr_set          = osd_attr_set,
3800         .do_ah_init           = osd_ah_init,
3801         .do_declare_create    = osd_declare_object_create,
3802         .do_create            = osd_object_ea_create,
3803         .do_declare_destroy   = osd_declare_object_destroy,
3804         .do_destroy           = osd_object_destroy,
3805         .do_index_try         = osd_index_try,
3806         .do_declare_ref_add   = osd_declare_object_ref_add,
3807         .do_ref_add           = osd_object_ref_add,
3808         .do_declare_ref_del   = osd_declare_object_ref_del,
3809         .do_ref_del           = osd_object_ref_del,
3810         .do_xattr_get         = osd_xattr_get,
3811         .do_declare_xattr_set = osd_declare_xattr_set,
3812         .do_xattr_set         = osd_xattr_set,
3813         .do_declare_xattr_del = osd_declare_xattr_del,
3814         .do_xattr_del         = osd_xattr_del,
3815         .do_xattr_list        = osd_xattr_list,
3816         .do_object_sync       = osd_object_sync,
3817 };
3818
3819 static const struct dt_object_operations osd_obj_otable_it_ops = {
3820         .do_attr_get    = osd_otable_it_attr_get,
3821         .do_index_try   = osd_index_try,
3822 };
3823
3824 static int osd_index_declare_iam_delete(const struct lu_env *env,
3825                                         struct dt_object *dt,
3826                                         const struct dt_key *key,
3827                                         struct thandle *handle)
3828 {
3829         struct osd_thandle    *oh;
3830
3831         oh = container_of0(handle, struct osd_thandle, ot_super);
3832         LASSERT(oh->ot_handle == NULL);
3833
3834         /* Recycle  may cause additional three blocks to be changed. */
3835         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3836                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
3837
3838         return 0;
3839 }
3840
3841 /**
3842  *      delete a (key, value) pair from index \a dt specified by \a key
3843  *
3844  *      \param  dt      osd index object
3845  *      \param  key     key for index
3846  *      \param  rec     record reference
3847  *      \param  handle  transaction handler
3848  *
3849  *      \retval  0  success
3850  *      \retval -ve   failure
3851  */
3852 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3853                                 const struct dt_key *key,
3854                                 struct thandle *handle)
3855 {
3856         struct osd_thread_info *oti = osd_oti_get(env);
3857         struct osd_object      *obj = osd_dt_obj(dt);
3858         struct osd_thandle     *oh;
3859         struct iam_path_descr  *ipd;
3860         struct iam_container   *bag = &obj->oo_dir->od_container;
3861         int                     rc;
3862         ENTRY;
3863
3864         if (!dt_object_exists(dt))
3865                 RETURN(-ENOENT);
3866
3867         LINVRNT(osd_invariant(obj));
3868         LASSERT(!dt_object_remote(dt));
3869         LASSERT(bag->ic_object == obj->oo_inode);
3870         LASSERT(handle != NULL);
3871
3872         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3873
3874         ipd = osd_idx_ipd_get(env, bag);
3875         if (unlikely(ipd == NULL))
3876                 RETURN(-ENOMEM);
3877
3878         oh = container_of0(handle, struct osd_thandle, ot_super);
3879         LASSERT(oh->ot_handle != NULL);
3880         LASSERT(oh->ot_handle->h_transaction != NULL);
3881
3882         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3883                 /* swab quota uid/gid provided by caller */
3884                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3885                 key = (const struct dt_key *)&oti->oti_quota_id;
3886         }
3887
3888         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3889         osd_ipd_put(env, bag, ipd);
3890         LINVRNT(osd_invariant(obj));
3891         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
3892         RETURN(rc);
3893 }
3894
3895 static int osd_index_declare_ea_delete(const struct lu_env *env,
3896                                        struct dt_object *dt,
3897                                        const struct dt_key *key,
3898                                        struct thandle *handle)
3899 {
3900         struct osd_thandle *oh;
3901         struct inode       *inode;
3902         int                 rc;
3903         ENTRY;
3904
3905         LASSERT(!dt_object_remote(dt));
3906         LASSERT(handle != NULL);
3907
3908         oh = container_of0(handle, struct osd_thandle, ot_super);
3909         LASSERT(oh->ot_handle == NULL);
3910
3911         /* due to DNE we may need to remove an agent inode */
3912         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3913                              osd_dto_credits_noquota[DTO_INDEX_DELETE] +
3914                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
3915
3916         inode = osd_dt_obj(dt)->oo_inode;
3917         if (inode == NULL)
3918                 RETURN(-ENOENT);
3919
3920         rc = osd_declare_inode_qid(env, i_uid_read(inode), i_gid_read(inode),
3921                                    0, oh, osd_dt_obj(dt), true, NULL, false);
3922         RETURN(rc);
3923 }
3924
3925 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3926                                           struct dt_rec *fid)
3927 {
3928         struct osd_fid_pack *rec;
3929         int                  rc = -ENODATA;
3930
3931         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3932                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3933                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3934                 if (rc == 0 && unlikely(!fid_is_sane((struct lu_fid *)fid)))
3935                         rc = -EINVAL;
3936         }
3937         return rc;
3938 }
3939
3940 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3941                           const struct lu_fid *fid)
3942 {
3943         struct seq_server_site  *ss = osd_seq_site(osd);
3944         ENTRY;
3945
3946         /* FID seqs not in FLDB, must be local seq */
3947         if (unlikely(!fid_seq_in_fldb(fid_seq(fid))))
3948                 RETURN(0);
3949
3950         /* If FLD is not being initialized yet, it only happens during the
3951          * initialization, likely during mgs initialization, and we assume
3952          * this is local FID. */
3953         if (ss == NULL || ss->ss_server_fld == NULL)
3954                 RETURN(0);
3955
3956         /* Only check the local FLDB here */
3957         if (osd_seq_exists(env, osd, fid_seq(fid)))
3958                 RETURN(0);
3959
3960         RETURN(1);
3961 }
3962
3963 /**
3964  * Index delete function for interoperability mode (b11826).
3965  * It will remove the directory entry added by osd_index_ea_insert().
3966  * This entry is needed to maintain name->fid mapping.
3967  *
3968  * \param key,  key i.e. file entry to be deleted
3969  *
3970  * \retval   0, on success
3971  * \retval -ve, on error
3972  */
3973 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3974                                const struct dt_key *key, struct thandle *handle)
3975 {
3976         struct osd_object          *obj = osd_dt_obj(dt);
3977         struct inode               *dir = obj->oo_inode;
3978         struct dentry              *dentry;
3979         struct osd_thandle         *oh;
3980         struct ldiskfs_dir_entry_2 *de = NULL;
3981         struct buffer_head         *bh;
3982         struct htree_lock          *hlock = NULL;
3983         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3984         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3985         int                        rc;
3986         ENTRY;
3987
3988         if (!dt_object_exists(dt))
3989                 RETURN(-ENOENT);
3990
3991         LINVRNT(osd_invariant(obj));
3992         LASSERT(!dt_object_remote(dt));
3993         LASSERT(handle != NULL);
3994
3995         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3996
3997         oh = container_of(handle, struct osd_thandle, ot_super);
3998         LASSERT(oh->ot_handle != NULL);
3999         LASSERT(oh->ot_handle->h_transaction != NULL);
4000
4001         ll_vfs_dq_init(dir);
4002         dentry = osd_child_dentry_get(env, obj,
4003                                       (char *)key, strlen((char *)key));
4004
4005         if (obj->oo_hl_head != NULL) {
4006                 hlock = osd_oti_get(env)->oti_hlock;
4007                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4008                                    dir, LDISKFS_HLOCK_DEL);
4009         } else {
4010                 down_write(&obj->oo_ext_idx_sem);
4011         }
4012
4013         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4014         if (bh) {
4015                 /* If this is not the ".." entry, it might be a remote DNE
4016                  * entry and  we need to check if the FID is for a remote
4017                  * MDT.  If the FID is  not in the directory entry (e.g.
4018                  * upgraded 1.8 filesystem without dirdata enabled) then
4019                  * we need to get the FID from the LMA. For a remote directory
4020                  * there HAS to be an LMA, it cannot be an IGIF inode in this
4021                  * case.
4022                  *
4023                  * Delete the entry before the agent inode in order to
4024                  * simplify error handling.  At worst an error after deleting
4025                  * the entry first might leak the agent inode afterward. The
4026                  * reverse would need filesystem abort in case of error deleting
4027                  * the entry after the agent had been removed, or leave a
4028                  * dangling entry pointing at a random inode. */
4029                 if (strcmp((char *)key, dotdot) != 0) {
4030                         LASSERT(de != NULL);
4031                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
4032                         if (rc == -ENODATA) {
4033                                 /* can't get FID, postpone to the end of the
4034                                  * transaction when iget() is safe */
4035                                 osd_schedule_agent_inode_removal(env, oh,
4036                                                 le32_to_cpu(de->inode));
4037                         } else if (rc == 0 &&
4038                                    unlikely(osd_remote_fid(env, osd, fid))) {
4039                                 osd_schedule_agent_inode_removal(env, oh,
4040                                                 le32_to_cpu(de->inode));
4041                         }
4042                 }
4043                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
4044                 brelse(bh);
4045         } else {
4046                 rc = -ENOENT;
4047         }
4048         if (hlock != NULL)
4049                 ldiskfs_htree_unlock(hlock);
4050         else
4051                 up_write(&obj->oo_ext_idx_sem);
4052
4053         if (rc != 0)
4054                 GOTO(out, rc);
4055
4056         /* For inode on the remote MDT, .. will point to
4057          * /Agent directory, Check whether it needs to delete
4058          * from agent directory */
4059         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
4060                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
4061                                                    oh);
4062                 if (rc != 0 && rc != -ENOENT) {
4063                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
4064                                osd_name(osd), PFID(fid), rc);
4065                 }
4066
4067                 if (rc == -ENOENT)
4068                         rc = 0;
4069
4070                 GOTO(out, rc);
4071         }
4072 out:
4073
4074         LASSERT(osd_invariant(obj));
4075         osd_trans_exec_check(env, handle, OSD_OT_DELETE);
4076         RETURN(rc);
4077 }
4078
4079 /**
4080  *      Lookup index for \a key and copy record to \a rec.
4081  *
4082  *      \param  dt      osd index object
4083  *      \param  key     key for index
4084  *      \param  rec     record reference
4085  *
4086  *      \retval  +ve  success : exact mach
4087  *      \retval  0    return record with key not greater than \a key
4088  *      \retval -ve   failure
4089  */
4090 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
4091                                 struct dt_rec *rec, const struct dt_key *key)
4092 {
4093         struct osd_object      *obj = osd_dt_obj(dt);
4094         struct iam_path_descr  *ipd;
4095         struct iam_container   *bag = &obj->oo_dir->od_container;
4096         struct osd_thread_info *oti = osd_oti_get(env);
4097         struct iam_iterator    *it = &oti->oti_idx_it;
4098         struct iam_rec         *iam_rec;
4099         int                     rc;
4100         ENTRY;
4101
4102         if (!dt_object_exists(dt))
4103                 RETURN(-ENOENT);
4104
4105         LASSERT(osd_invariant(obj));
4106         LASSERT(!dt_object_remote(dt));
4107         LASSERT(bag->ic_object == obj->oo_inode);
4108
4109         ipd = osd_idx_ipd_get(env, bag);
4110         if (IS_ERR(ipd))
4111                 RETURN(-ENOMEM);
4112
4113         /* got ipd now we can start iterator. */
4114         iam_it_init(it, bag, 0, ipd);
4115
4116         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
4117                 /* swab quota uid/gid provided by caller */
4118                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4119                 key = (const struct dt_key *)&oti->oti_quota_id;
4120         }
4121
4122         rc = iam_it_get(it, (struct iam_key *)key);
4123         if (rc >= 0) {
4124                 if (S_ISDIR(obj->oo_inode->i_mode))
4125                         iam_rec = (struct iam_rec *)oti->oti_ldp;
4126                 else
4127                         iam_rec = (struct iam_rec *) rec;
4128
4129                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
4130
4131                 if (S_ISDIR(obj->oo_inode->i_mode))
4132                         osd_fid_unpack((struct lu_fid *) rec,
4133                                        (struct osd_fid_pack *)iam_rec);
4134                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
4135                         osd_quota_unpack(obj, rec);
4136         }
4137
4138         iam_it_put(it);
4139         iam_it_fini(it);
4140         osd_ipd_put(env, bag, ipd);
4141
4142         LINVRNT(osd_invariant(obj));
4143
4144         RETURN(rc);
4145 }
4146
4147 static int osd_index_declare_iam_insert(const struct lu_env *env,
4148                                         struct dt_object *dt,
4149                                         const struct dt_rec *rec,
4150                                         const struct dt_key *key,
4151                                         struct thandle *handle)
4152 {
4153         struct osd_thandle *oh;
4154
4155         LASSERT(handle != NULL);
4156
4157         oh = container_of0(handle, struct osd_thandle, ot_super);
4158         LASSERT(oh->ot_handle == NULL);
4159
4160         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4161                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4162
4163         return 0;
4164 }
4165
4166 /**
4167  *      Inserts (key, value) pair in \a dt index object.
4168  *
4169  *      \param  dt      osd index object
4170  *      \param  key     key for index
4171  *      \param  rec     record reference
4172  *      \param  th      transaction handler
4173  *
4174  *      \retval  0  success
4175  *      \retval -ve failure
4176  */
4177 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
4178                                 const struct dt_rec *rec,
4179                                 const struct dt_key *key, struct thandle *th,
4180                                 int ignore_quota)
4181 {
4182         struct osd_object     *obj = osd_dt_obj(dt);
4183         struct iam_path_descr *ipd;
4184         struct osd_thandle    *oh;
4185         struct iam_container  *bag;
4186         struct osd_thread_info *oti = osd_oti_get(env);
4187         struct iam_rec         *iam_rec;
4188         int                     rc;
4189         ENTRY;
4190
4191         if (!dt_object_exists(dt))
4192                 RETURN(-ENOENT);
4193
4194         LINVRNT(osd_invariant(obj));
4195         LASSERT(!dt_object_remote(dt));
4196
4197         bag = &obj->oo_dir->od_container;
4198         LASSERT(bag->ic_object == obj->oo_inode);
4199         LASSERT(th != NULL);
4200
4201         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4202
4203         ipd = osd_idx_ipd_get(env, bag);
4204         if (unlikely(ipd == NULL))
4205                 RETURN(-ENOMEM);
4206
4207         oh = container_of0(th, struct osd_thandle, ot_super);
4208         LASSERT(oh->ot_handle != NULL);
4209         LASSERT(oh->ot_handle->h_transaction != NULL);
4210         if (S_ISDIR(obj->oo_inode->i_mode)) {
4211                 iam_rec = (struct iam_rec *)oti->oti_ldp;
4212                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
4213         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
4214                 /* pack quota uid/gid */
4215                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4216                 key = (const struct dt_key *)&oti->oti_quota_id;
4217                 /* pack quota record */
4218                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
4219                 iam_rec = (struct iam_rec *)rec;
4220         } else {
4221                 iam_rec = (struct iam_rec *)rec;
4222         }
4223
4224         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
4225                         iam_rec, ipd);
4226         osd_ipd_put(env, bag, ipd);
4227         LINVRNT(osd_invariant(obj));
4228         osd_trans_exec_check(env, th, OSD_OT_INSERT);
4229         RETURN(rc);
4230 }
4231
4232 /**
4233  * Calls ldiskfs_add_entry() to add directory entry
4234  * into the directory. This is required for
4235  * interoperability mode (b11826)
4236  *
4237  * \retval   0, on success
4238  * \retval -ve, on error
4239  */
4240 static int __osd_ea_add_rec(struct osd_thread_info *info,
4241                             struct osd_object *pobj, struct inode  *cinode,
4242                             const char *name, const struct lu_fid *fid,
4243                             struct htree_lock *hlock, struct thandle *th)
4244 {
4245         struct ldiskfs_dentry_param *ldp;
4246         struct dentry               *child;
4247         struct osd_thandle          *oth;
4248         int                          rc;
4249
4250         oth = container_of(th, struct osd_thandle, ot_super);
4251         LASSERT(oth->ot_handle != NULL);
4252         LASSERT(oth->ot_handle->h_transaction != NULL);
4253         LASSERT(pobj->oo_inode);
4254
4255         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
4256         if (unlikely(pobj->oo_inode ==
4257                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
4258                 ldp->edp_magic = 0;
4259         else
4260                 osd_get_ldiskfs_dirent_param(ldp, fid);
4261         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
4262         child->d_fsdata = (void *)ldp;
4263         ll_vfs_dq_init(pobj->oo_inode);
4264         rc = osd_ldiskfs_add_entry(info, oth->ot_handle, child,
4265                                    cinode, hlock);
4266         if (rc == 0 && OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_TYPE)) {
4267                 struct ldiskfs_dir_entry_2      *de;
4268                 struct buffer_head              *bh;
4269                 int                              rc1;
4270
4271                 bh = osd_ldiskfs_find_entry(pobj->oo_inode, &child->d_name, &de,
4272                                             NULL, hlock);
4273                 if (bh != NULL) {
4274                         rc1 = ldiskfs_journal_get_write_access(oth->ot_handle,
4275                                                                bh);
4276                         if (rc1 == 0) {
4277                                 if (S_ISDIR(cinode->i_mode))
4278                                         de->file_type = LDISKFS_DIRENT_LUFID |
4279                                                         LDISKFS_FT_REG_FILE;
4280                                 else
4281                                         de->file_type = LDISKFS_DIRENT_LUFID |
4282                                                         LDISKFS_FT_DIR;
4283                                 ldiskfs_handle_dirty_metadata(oth->ot_handle,
4284                                                               NULL, bh);
4285                                 brelse(bh);
4286                         }
4287                 }
4288         }
4289
4290         RETURN(rc);
4291 }
4292
4293 /**
4294  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
4295  * into the directory.Also sets flags into osd object to
4296  * indicate dot and dotdot are created. This is required for
4297  * interoperability mode (b11826)
4298  *
4299  * \param dir   directory for dot and dotdot fixup.
4300  * \param obj   child object for linking
4301  *
4302  * \retval   0, on success
4303  * \retval -ve, on error
4304  */
4305 static int osd_add_dot_dotdot(struct osd_thread_info *info,
4306                               struct osd_object *dir,
4307                               struct inode *parent_dir, const char *name,
4308                               const struct lu_fid *dot_fid,
4309                               const struct lu_fid *dot_dot_fid,
4310                               struct thandle *th)
4311 {
4312         struct inode                *inode = dir->oo_inode;
4313         struct osd_thandle          *oth;
4314         int result = 0;
4315
4316         oth = container_of(th, struct osd_thandle, ot_super);
4317         LASSERT(oth->ot_handle->h_transaction != NULL);
4318         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
4319
4320         if (strcmp(name, dot) == 0) {
4321                 if (dir->oo_compat_dot_created) {
4322                         result = -EEXIST;
4323                 } else {
4324                         LASSERT(inode->i_ino == parent_dir->i_ino);
4325                         dir->oo_compat_dot_created = 1;
4326                         result = 0;
4327                 }
4328         } else if (strcmp(name, dotdot) == 0) {
4329                 if (!dir->oo_compat_dot_created)
4330                         return -EINVAL;
4331                 /* in case of rename, dotdot is already created */
4332                 if (dir->oo_compat_dotdot_created) {
4333                         return __osd_ea_add_rec(info, dir, parent_dir, name,
4334                                                 dot_dot_fid, NULL, th);
4335                 }
4336
4337                 if (OBD_FAIL_CHECK(OBD_FAIL_LFSCK_BAD_PARENT)) {
4338                         struct lu_fid tfid = *dot_dot_fid;
4339
4340                         tfid.f_oid--;
4341                         result = osd_add_dot_dotdot_internal(info,
4342                                         dir->oo_inode, parent_dir, dot_fid,
4343                                         &tfid, oth);
4344                 } else {
4345                         result = osd_add_dot_dotdot_internal(info,
4346                                         dir->oo_inode, parent_dir, dot_fid,
4347                                         dot_dot_fid, oth);
4348                 }
4349
4350                 if (result == 0)
4351                         dir->oo_compat_dotdot_created = 1;
4352         }
4353
4354         return result;
4355 }
4356
4357
4358 /**
4359  * It will call the appropriate osd_add* function and return the
4360  * value, return by respective functions.
4361  */
4362 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
4363                           struct inode *cinode, const char *name,
4364                           const struct lu_fid *fid, struct thandle *th)
4365 {
4366         struct osd_thread_info *info   = osd_oti_get(env);
4367         struct htree_lock      *hlock;
4368         int                     rc;
4369
4370         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
4371
4372         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
4373                                                    name[2] =='\0'))) {
4374                 if (hlock != NULL) {
4375                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
4376                                            pobj->oo_inode, 0);
4377                 } else {
4378                         down_write(&pobj->oo_ext_idx_sem);
4379                 }
4380
4381                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
4382                                         lu_object_fid(&pobj->oo_dt.do_lu),
4383                                         fid, th);
4384         } else {
4385                 if (hlock != NULL) {
4386                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
4387                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
4388                 } else {
4389                         down_write(&pobj->oo_ext_idx_sem);
4390                 }
4391
4392                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
4393                         struct lu_fid *tfid = &info->oti_fid;
4394
4395                         *tfid = *fid;
4396                         tfid->f_ver = ~0;
4397                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
4398                                               tfid, hlock, th);
4399                 } else {
4400                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
4401                                               hlock, th);
4402                 }
4403         }
4404         if (hlock != NULL)
4405                 ldiskfs_htree_unlock(hlock);
4406         else
4407                 up_write(&pobj->oo_ext_idx_sem);
4408
4409         return rc;
4410 }
4411
4412 static int
4413 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
4414                       struct osd_idmap_cache *oic)
4415 {
4416         struct osd_scrub    *scrub = &dev->od_scrub;
4417         struct lu_fid       *fid   = &oic->oic_fid;
4418         struct osd_inode_id *id    = &oti->oti_id;
4419         int                  once  = 0;
4420         int                  rc;
4421         ENTRY;
4422
4423         if (!fid_is_norm(fid) && !fid_is_igif(fid))
4424                 RETURN(0);
4425
4426         if (scrub->os_pos_current > id->oii_ino)
4427                 RETURN(0);
4428
4429 again:
4430         rc = osd_oi_lookup(oti, dev, fid, id, 0);
4431         if (rc == -ENOENT) {
4432                 struct inode *inode;
4433
4434                 *id = oic->oic_lid;
4435                 inode = osd_iget(oti, dev, &oic->oic_lid);
4436
4437                 /* The inode has been removed (by race maybe). */
4438                 if (IS_ERR(inode)) {
4439                         rc = PTR_ERR(inode);
4440
4441                         RETURN(rc == -ESTALE ? -ENOENT : rc);
4442                 }
4443
4444                 iput(inode);
4445                 /* The OI mapping is lost. */
4446                 if (id->oii_gen != OSD_OII_NOGEN)
4447                         goto trigger;
4448
4449                 /* The inode may has been reused by others, we do not know,
4450                  * leave it to be handled by subsequent osd_fid_lookup(). */
4451                 RETURN(0);
4452         } else if (rc != 0 || osd_id_eq(id, &oic->oic_lid)) {
4453                 RETURN(rc);
4454         }
4455
4456 trigger:
4457         if (thread_is_running(&scrub->os_thread)) {
4458                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
4459                 /* There is race condition between osd_oi_lookup and OI scrub.
4460                  * The OI scrub finished just after osd_oi_lookup() failure.
4461                  * Under such case, it is unnecessary to trigger OI scrub again,
4462                  * but try to call osd_oi_lookup() again. */
4463                 if (unlikely(rc == -EAGAIN))
4464                         goto again;
4465
4466                 RETURN(0);
4467         }
4468
4469         if (!dev->od_noscrub && ++once == 1) {
4470                 rc = osd_scrub_start(dev, SS_AUTO_PARTIAL | SS_CLEAR_DRYRUN |
4471                                      SS_CLEAR_FAILOUT);
4472                 CDEBUG(D_LFSCK | D_CONSOLE, "%.16s: trigger OI scrub by RPC "
4473                        "for "DFID", rc = %d [2]\n",
4474                        LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
4475                        PFID(fid), rc);
4476                 if (rc == 0 || rc == -EALREADY)
4477                         goto again;
4478         }
4479
4480         RETURN(0);
4481 }
4482
4483 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
4484                                struct osd_device *dev,
4485                                struct osd_idmap_cache *oic,
4486                                struct lu_fid *fid, __u32 ino)
4487 {
4488         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
4489         struct inode            *inode;
4490         int                      rc;
4491
4492         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
4493         inode = osd_iget(oti, dev, &oic->oic_lid);
4494         if (IS_ERR(inode)) {
4495                 fid_zero(&oic->oic_fid);
4496                 return PTR_ERR(inode);
4497         }
4498
4499         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
4500         iput(inode);
4501         if (rc != 0)
4502                 fid_zero(&oic->oic_fid);
4503         else
4504                 *fid = oic->oic_fid = lma->lma_self_fid;
4505         return rc;
4506 }
4507
4508 void osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
4509                       struct osd_inode_id *id, const struct lu_fid *fid)
4510 {
4511         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
4512                id->oii_ino, id->oii_gen, info);
4513         info->oti_cache.oic_lid = *id;
4514         info->oti_cache.oic_fid = *fid;
4515         info->oti_cache.oic_dev = osd;
4516 }
4517
4518 /**
4519  * Get parent FID from the linkEA.
4520  *
4521  * For a directory which parent resides on remote MDT, to satisfy the
4522  * local e2fsck, we insert it into the /REMOTE_PARENT_DIR locally. On
4523  * the other hand, to make the lookup(..) on the directory can return
4524  * the real parent FID, we append the real parent FID after its ".."
4525  * name entry in the /REMOTE_PARENT_DIR.
4526  *
4527  * Unfortunately, such PFID-in-dirent cannot be preserved via file-level
4528  * backup. So after the restore, we cannot get the right parent FID from
4529  * its ".." name entry in the /REMOTE_PARENT_DIR. Under such case, since
4530  * we have stored the real parent FID in the directory object's linkEA,
4531  * we can parse the linkEA for the real parent FID.
4532  *
4533  * \param[in] env       pointer to the thread context
4534  * \param[in] obj       pointer to the object to be handled
4535  * \param[out]fid       pointer to the buffer to hold the parent FID
4536  *
4537  * \retval              0 for getting the real parent FID successfully
4538  * \retval              negative error number on failure
4539  */
4540 static int osd_get_pfid_from_linkea(const struct lu_env *env,
4541                                     struct osd_object *obj,
4542                                     struct lu_fid *fid)
4543 {
4544         struct osd_thread_info  *oti    = osd_oti_get(env);
4545         struct lu_buf           *buf    = &oti->oti_big_buf;
4546         struct dentry           *dentry = &oti->oti_obj_dentry;
4547         struct inode            *inode  = obj->oo_inode;
4548         struct linkea_data       ldata  = { NULL };
4549         int                      rc;
4550         ENTRY;
4551
4552         fid_zero(fid);
4553         if (!S_ISDIR(inode->i_mode))
4554                 RETURN(-EIO);
4555
4556 again:
4557         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
4558                              buf->lb_buf, buf->lb_len);
4559         if (rc == -ERANGE) {
4560                 rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LINK,
4561                                      NULL, 0);
4562                 if (rc > 0) {
4563                         lu_buf_realloc(buf, rc);
4564                         if (buf->lb_buf == NULL)
4565                                 RETURN(-ENOMEM);
4566
4567                         goto again;
4568                 }
4569         }
4570
4571         if (unlikely(rc == 0))
4572                 RETURN(-ENODATA);
4573
4574         if (rc < 0)
4575                 RETURN(rc);
4576
4577         if (unlikely(buf->lb_buf == NULL)) {
4578                 lu_buf_realloc(buf, rc);
4579                 if (buf->lb_buf == NULL)
4580                         RETURN(-ENOMEM);
4581
4582                 goto again;
4583         }
4584
4585         ldata.ld_buf = buf;
4586         rc = linkea_init(&ldata);
4587         if (rc == 0) {
4588                 linkea_first_entry(&ldata);
4589                 linkea_entry_unpack(ldata.ld_lee, &ldata.ld_reclen, NULL, fid);
4590         }
4591
4592         RETURN(rc);
4593 }
4594
4595 /**
4596  * Calls ->lookup() to find dentry. From dentry get inode and
4597  * read inode's ea to get fid. This is required for  interoperability
4598  * mode (b11826)
4599  *
4600  * \retval   0, on success
4601  * \retval -ve, on error
4602  */
4603 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
4604                              struct dt_rec *rec, const struct dt_key *key)
4605 {
4606         struct inode                    *dir    = obj->oo_inode;
4607         struct dentry                   *dentry;
4608         struct ldiskfs_dir_entry_2      *de;
4609         struct buffer_head              *bh;
4610         struct lu_fid                   *fid = (struct lu_fid *) rec;
4611         struct htree_lock               *hlock = NULL;
4612         int                             ino;
4613         int                             rc;
4614         ENTRY;
4615
4616         LASSERT(dir->i_op != NULL);
4617         LASSERT(dir->i_op->lookup != NULL);
4618
4619         dentry = osd_child_dentry_get(env, obj,
4620                                       (char *)key, strlen((char *)key));
4621
4622         if (obj->oo_hl_head != NULL) {
4623                 hlock = osd_oti_get(env)->oti_hlock;
4624                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4625                                    dir, LDISKFS_HLOCK_LOOKUP);
4626         } else {
4627                 down_read(&obj->oo_ext_idx_sem);
4628         }
4629
4630         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
4631         if (bh) {
4632                 struct osd_thread_info *oti = osd_oti_get(env);
4633                 struct osd_inode_id *id = &oti->oti_id;
4634                 struct osd_idmap_cache *oic = &oti->oti_cache;
4635                 struct osd_device *dev = osd_obj2dev(obj);
4636
4637                 ino = le32_to_cpu(de->inode);
4638                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
4639                         brelse(bh);
4640                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
4641                         GOTO(out, rc);
4642                 }
4643
4644                 rc = osd_get_fid_from_dentry(de, rec);
4645
4646                 /* done with de, release bh */
4647                 brelse(bh);
4648                 if (rc != 0) {
4649                         if (unlikely(ino == osd_remote_parent_ino(dev))) {
4650                                 const char *name = (const char *)key;
4651
4652                                 /* If the parent is on remote MDT, and there
4653                                  * is no FID-in-dirent, then we have to get
4654                                  * the parent FID from the linkEA.  */
4655                                 if (likely(strlen(name) == 2 &&
4656                                            name[0] == '.' && name[1] == '.'))
4657                                         rc = osd_get_pfid_from_linkea(env, obj,
4658                                                                       fid);
4659                         } else {
4660                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
4661                         }
4662                 } else {
4663                         osd_id_gen(id, ino, OSD_OII_NOGEN);
4664                 }
4665
4666                 if (rc != 0 || osd_remote_fid(env, dev, fid)) {
4667                         fid_zero(&oic->oic_fid);
4668
4669                         GOTO(out, rc);
4670                 }
4671
4672                 osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id, fid);
4673                 rc = osd_consistency_check(oti, dev, oic);
4674                 if (rc != 0)
4675                         fid_zero(&oic->oic_fid);
4676         } else {
4677                 rc = -ENOENT;
4678         }
4679
4680         GOTO(out, rc);
4681
4682 out:
4683         if (hlock != NULL)
4684                 ldiskfs_htree_unlock(hlock);
4685         else
4686                 up_read(&obj->oo_ext_idx_sem);
4687         return rc;
4688 }
4689
4690 /**
4691  * Put the osd object once done with it.
4692  *
4693  * \param obj osd object that needs to be put
4694  */
4695 static inline void osd_object_put(const struct lu_env *env,
4696                                   struct osd_object *obj)
4697 {
4698         lu_object_put(env, &obj->oo_dt.do_lu);
4699 }
4700
4701 static int osd_index_declare_ea_insert(const struct lu_env *env,
4702                                        struct dt_object *dt,
4703                                        const struct dt_rec *rec,
4704                                        const struct dt_key *key,
4705                                        struct thandle *handle)
4706 {
4707         struct osd_thandle      *oh;
4708         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4709         struct dt_insert_rec    *rec1   = (struct dt_insert_rec *)rec;
4710         const struct lu_fid     *fid    = rec1->rec_fid;
4711         int                      credits, rc = 0;
4712         struct osd_idmap_cache  *idc;
4713         ENTRY;
4714
4715         LASSERT(!dt_object_remote(dt));
4716         LASSERT(handle != NULL);
4717         LASSERT(fid != NULL);
4718         LASSERT(rec1->rec_type != 0);
4719
4720         oh = container_of0(handle, struct osd_thandle, ot_super);
4721         LASSERT(oh->ot_handle == NULL);
4722
4723         credits = osd_dto_credits_noquota[DTO_INDEX_INSERT];
4724
4725         /* we can't call iget() while a transactions is running
4726          * (this can lead to a deadlock), but we need to know
4727          * inum and object type. so we find this information at
4728          * declaration and cache in per-thread info */
4729         idc = osd_idc_find_or_init(env, osd, fid);
4730         if (IS_ERR(idc))
4731                 RETURN(PTR_ERR(idc));
4732         if (idc->oic_remote) {
4733                 /* a reference to remote inode is represented by an
4734                  * agent inode which we have to create */
4735                 credits += osd_dto_credits_noquota[DTO_OBJECT_CREATE];
4736                 credits += osd_dto_credits_noquota[DTO_INDEX_INSERT];
4737         }
4738
4739         osd_trans_declare_op(env, oh, OSD_OT_INSERT, credits);
4740
4741         if (osd_dt_obj(dt)->oo_inode != NULL) {
4742                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4743
4744                 /* We ignore block quota on meta pool (MDTs), so needn't
4745                  * calculate how many blocks will be consumed by this index
4746                  * insert */
4747                 rc = osd_declare_inode_qid(env, i_uid_read(inode),
4748                                            i_gid_read(inode), 0, oh,
4749                                            osd_dt_obj(dt), true, NULL, false);
4750         }
4751
4752         RETURN(rc);
4753 }
4754
4755 /**
4756  * Index add function for interoperability mode (b11826).
4757  * It will add the directory entry.This entry is needed to
4758  * maintain name->fid mapping.
4759  *
4760  * \param key it is key i.e. file entry to be inserted
4761  * \param rec it is value of given key i.e. fid
4762  *
4763  * \retval   0, on success
4764  * \retval -ve, on error
4765  */
4766 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4767                                const struct dt_rec *rec,
4768                                const struct dt_key *key, struct thandle *th,
4769                                int ignore_quota)
4770 {
4771         struct osd_object       *obj = osd_dt_obj(dt);
4772         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4773         struct dt_insert_rec    *rec1   = (struct dt_insert_rec *)rec;
4774         const struct lu_fid     *fid    = rec1->rec_fid;
4775         const char              *name = (const char *)key;
4776         struct osd_thread_info  *oti   = osd_oti_get(env);
4777         struct inode            *child_inode = NULL;
4778         struct osd_idmap_cache  *idc;
4779         int                     rc;
4780         ENTRY;
4781
4782         if (!dt_object_exists(dt))
4783                 RETURN(-ENOENT);
4784
4785         LASSERT(osd_invariant(obj));
4786         LASSERT(!dt_object_remote(dt));
4787         LASSERT(th != NULL);
4788
4789         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4790
4791         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!\n", PFID(fid));
4792
4793         idc = osd_idc_find(env, osd, fid);
4794         if (unlikely(idc == NULL)) {
4795                 /* this dt_insert() wasn't declared properly, so
4796                  * FID is missing in OI cache. we better do not
4797                  * lookup FID in FLDB/OI and don't risk to deadlock,
4798                  * but in some special cases (lfsck testing, etc)
4799                  * it's much simpler than fixing a caller */
4800                 CERROR("%s: "DFID" wasn't declared for insert\n",
4801                        osd_name(osd), PFID(fid));
4802                 dump_stack();
4803                 idc = osd_idc_find_or_init(env, osd, fid);
4804                 if (IS_ERR(idc))
4805                         RETURN(PTR_ERR(idc));
4806         }
4807
4808         if (idc->oic_remote) {
4809                 /* Insert remote entry */
4810                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4811                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4812                         struct osd_thandle      *oh;
4813
4814                         /* If parent on remote MDT, we need put this object
4815                          * under AGENT */
4816                         oh = container_of(th, typeof(*oh), ot_super);
4817                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4818                         if (rc != 0) {
4819                                 CERROR("%s: add "DFID" error: rc = %d\n",
4820                                        osd_name(osd),
4821                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4822                                 RETURN(rc);
4823                         }
4824
4825                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4826                 } else {
4827                         child_inode = osd_create_local_agent_inode(env, osd,
4828                                         obj, fid, rec1->rec_type & S_IFMT, th);
4829                         if (IS_ERR(child_inode))
4830                                 RETURN(PTR_ERR(child_inode));
4831                 }
4832         } else {
4833                 /* Insert local entry */
4834                 if (unlikely(idc->oic_lid.oii_ino == 0)) {
4835                         /* for a reason OI cache wasn't filled properly */
4836                         CERROR("%s: OIC for "DFID" isn't filled\n",
4837                                osd_name(osd), PFID(fid));
4838                         RETURN(-EINVAL);
4839                 }
4840                 child_inode = oti->oti_inode;
4841                 if (unlikely(child_inode == NULL)) {
4842                         struct ldiskfs_inode_info *lii;
4843                         OBD_ALLOC_PTR(lii);
4844                         if (lii == NULL)
4845                                 RETURN(-ENOMEM);
4846                         child_inode = oti->oti_inode = &lii->vfs_inode;
4847                 }
4848                 child_inode->i_sb = osd_sb(osd);
4849                 child_inode->i_ino = idc->oic_lid.oii_ino;
4850                 child_inode->i_mode = rec1->rec_type & S_IFMT;
4851         }
4852
4853         rc = osd_ea_add_rec(env, obj, child_inode, name, fid, th);
4854
4855         CDEBUG(D_INODE, "parent %lu insert %s:%lu rc = %d\n",
4856                obj->oo_inode->i_ino, name, child_inode->i_ino, rc);
4857
4858         if (child_inode && child_inode != oti->oti_inode)
4859                 iput(child_inode);
4860         LASSERT(osd_invariant(obj));
4861         osd_trans_exec_check(env, th, OSD_OT_INSERT);
4862         RETURN(rc);
4863 }
4864
4865 /**
4866  *  Initialize osd Iterator for given osd index object.
4867  *
4868  *  \param  dt      osd index object
4869  */
4870
4871 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4872                                      struct dt_object *dt,
4873                                      __u32 unused)
4874 {
4875         struct osd_it_iam      *it;
4876         struct osd_object      *obj = osd_dt_obj(dt);
4877         struct lu_object       *lo  = &dt->do_lu;
4878         struct iam_path_descr  *ipd;
4879         struct iam_container   *bag = &obj->oo_dir->od_container;
4880
4881         if (!dt_object_exists(dt))
4882                 return ERR_PTR(-ENOENT);
4883
4884         OBD_ALLOC_PTR(it);
4885         if (it == NULL)
4886                 return ERR_PTR(-ENOMEM);
4887
4888         ipd = osd_it_ipd_get(env, bag);
4889         if (likely(ipd != NULL)) {
4890                 it->oi_obj = obj;
4891                 it->oi_ipd = ipd;
4892                 lu_object_get(lo);
4893                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4894                 return (struct dt_it *)it;
4895         } else {
4896                 OBD_FREE_PTR(it);
4897                 return ERR_PTR(-ENOMEM);
4898         }
4899 }
4900
4901 /**
4902  * free given Iterator.
4903  */
4904
4905 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4906 {
4907         struct osd_it_iam       *it  = (struct osd_it_iam *)di;
4908         struct osd_object       *obj = it->oi_obj;
4909
4910         iam_it_fini(&it->oi_it);
4911         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4912         lu_object_put(env, &obj->oo_dt.do_lu);
4913         OBD_FREE_PTR(it);
4914 }
4915
4916 /**
4917  *  Move Iterator to record specified by \a key
4918  *
4919  *  \param  di      osd iterator
4920  *  \param  key     key for index
4921  *
4922  *  \retval +ve  di points to record with least key not larger than key
4923  *  \retval  0   di points to exact matched key
4924  *  \retval -ve  failure
4925  */
4926
4927 static int osd_it_iam_get(const struct lu_env *env,
4928                           struct dt_it *di, const struct dt_key *key)
4929 {
4930         struct osd_thread_info  *oti = osd_oti_get(env);
4931         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4932
4933         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4934                 /* swab quota uid/gid */
4935                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4936                 key = (struct dt_key *)&oti->oti_quota_id;
4937         }
4938
4939         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4940 }
4941
4942 /**
4943  *  Release Iterator
4944  *
4945  *  \param  di      osd iterator
4946  */
4947 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4948 {
4949         struct osd_it_iam *it = (struct osd_it_iam *)di;
4950
4951         iam_it_put(&it->oi_it);
4952 }
4953
4954 /**
4955  *  Move iterator by one record
4956  *
4957  *  \param  di      osd iterator
4958  *
4959  *  \retval +1   end of container reached
4960  *  \retval  0   success
4961  *  \retval -ve  failure
4962  */
4963
4964 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4965 {
4966         struct osd_it_iam *it = (struct osd_it_iam *)di;
4967
4968         return iam_it_next(&it->oi_it);
4969 }
4970
4971 /**
4972  * Return pointer to the key under iterator.
4973  */
4974
4975 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4976                                  const struct dt_it *di)
4977 {
4978         struct osd_thread_info *oti = osd_oti_get(env);
4979         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4980         struct osd_object      *obj = it->oi_obj;
4981         struct dt_key          *key;
4982
4983         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4984
4985         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4986                 /* swab quota uid/gid */
4987                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4988                 key = (struct dt_key *)&oti->oti_quota_id;
4989         }
4990
4991         return key;
4992 }
4993
4994 /**
4995  * Return size of key under iterator (in bytes)
4996  */
4997
4998 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4999 {
5000         struct osd_it_iam *it = (struct osd_it_iam *)di;
5001
5002         return iam_it_key_size(&it->oi_it);
5003 }
5004
5005 static inline void
5006 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
5007 {
5008         /* check if file type is required */
5009         if (ent->lde_attrs & LUDA_TYPE) {
5010                 struct luda_type *lt;
5011                 int align = sizeof(*lt) - 1;
5012
5013                 len = (len + align) & ~align;
5014                 lt = (struct luda_type *)(ent->lde_name + len);
5015                 lt->lt_type = cpu_to_le16(DTTOIF(type));
5016         }
5017
5018         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
5019 }
5020
5021 /**
5022  * build lu direct from backend fs dirent.
5023  */
5024
5025 static inline void
5026 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
5027                    char *name, __u16 namelen, __u16 type, __u32 attr)
5028 {
5029         ent->lde_attrs = attr | LUDA_FID;
5030         fid_cpu_to_le(&ent->lde_fid, fid);
5031
5032         ent->lde_hash = cpu_to_le64(offset);
5033         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
5034
5035         strncpy(ent->lde_name, name, namelen);
5036         ent->lde_name[namelen] = '\0';
5037         ent->lde_namelen = cpu_to_le16(namelen);
5038
5039         /* append lustre attributes */
5040         osd_it_append_attrs(ent, namelen, type);
5041 }
5042
5043 /**
5044  * Return pointer to the record under iterator.
5045  */
5046 static int osd_it_iam_rec(const struct lu_env *env,
5047                           const struct dt_it *di,
5048                           struct dt_rec *dtrec, __u32 attr)
5049 {
5050         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
5051         struct osd_thread_info *info = osd_oti_get(env);
5052         ENTRY;
5053
5054         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
5055                 const struct osd_fid_pack *rec;
5056                 struct lu_fid             *fid = &info->oti_fid;
5057                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
5058                 char                      *name;
5059                 int                        namelen;
5060                 __u64                      hash;
5061                 int                        rc;
5062
5063                 name = (char *)iam_it_key_get(&it->oi_it);
5064                 if (IS_ERR(name))
5065                         RETURN(PTR_ERR(name));
5066
5067                 namelen = iam_it_key_size(&it->oi_it);
5068
5069                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
5070                 if (IS_ERR(rec))
5071                         RETURN(PTR_ERR(rec));
5072
5073                 rc = osd_fid_unpack(fid, rec);
5074                 if (rc)
5075                         RETURN(rc);
5076
5077                 hash = iam_it_store(&it->oi_it);
5078
5079                 /* IAM does not store object type in IAM index (dir) */
5080                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
5081                                    0, LUDA_FID);
5082         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
5083                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
5084                            (struct iam_rec *)dtrec);
5085                 osd_quota_unpack(it->oi_obj, dtrec);
5086         } else {
5087                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
5088                            (struct iam_rec *)dtrec);
5089         }
5090
5091         RETURN(0);
5092 }
5093
5094 /**
5095  * Returns cookie for current Iterator position.
5096  */
5097 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
5098 {
5099         struct osd_it_iam *it = (struct osd_it_iam *)di;
5100
5101         return iam_it_store(&it->oi_it);
5102 }
5103
5104 /**
5105  * Restore iterator from cookie.
5106  *
5107  * \param  di      osd iterator
5108  * \param  hash    Iterator location cookie
5109  *
5110  * \retval +ve  di points to record with least key not larger than key.
5111  * \retval  0   di points to exact matched key
5112  * \retval -ve  failure
5113  */
5114
5115 static int osd_it_iam_load(const struct lu_env *env,
5116                            const struct dt_it *di, __u64 hash)
5117 {
5118         struct osd_it_iam *it = (struct osd_it_iam *)di;
5119
5120         return iam_it_load(&it->oi_it, hash);
5121 }
5122
5123 static const struct dt_index_operations osd_index_iam_ops = {
5124         .dio_lookup         = osd_index_iam_lookup,
5125         .dio_declare_insert = osd_index_declare_iam_insert,
5126         .dio_insert         = osd_index_iam_insert,
5127         .dio_declare_delete = osd_index_declare_iam_delete,
5128         .dio_delete         = osd_index_iam_delete,
5129         .dio_it     = {
5130                 .init     = osd_it_iam_init,
5131                 .fini     = osd_it_iam_fini,
5132                 .get      = osd_it_iam_get,
5133                 .put      = osd_it_iam_put,
5134                 .next     = osd_it_iam_next,
5135                 .key      = osd_it_iam_key,
5136                 .key_size = osd_it_iam_key_size,
5137                 .rec      = osd_it_iam_rec,
5138                 .store    = osd_it_iam_store,
5139                 .load     = osd_it_iam_load
5140         }
5141 };
5142
5143
5144 /**
5145  * Creates or initializes iterator context.
5146  *
5147  * \retval struct osd_it_ea, iterator structure on success
5148  *
5149  */
5150 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
5151                                     struct dt_object *dt,
5152                                     __u32 attr)
5153 {
5154         struct osd_object       *obj  = osd_dt_obj(dt);
5155         struct osd_thread_info  *info = osd_oti_get(env);
5156         struct osd_it_ea        *oie;
5157         struct file             *file;
5158         struct lu_object        *lo   = &dt->do_lu;
5159         struct dentry           *obj_dentry;
5160         ENTRY;
5161
5162         if (!dt_object_exists(dt) || obj->oo_destroyed)
5163                 RETURN(ERR_PTR(-ENOENT));
5164
5165         OBD_SLAB_ALLOC_PTR_GFP(oie, osd_itea_cachep, GFP_NOFS);
5166         if (oie == NULL)
5167                 RETURN(ERR_PTR(-ENOMEM));
5168         obj_dentry = &oie->oie_dentry;
5169
5170         obj_dentry->d_inode = obj->oo_inode;
5171         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
5172         obj_dentry->d_name.hash = 0;
5173
5174         oie->oie_rd_dirent       = 0;
5175         oie->oie_it_dirent       = 0;
5176         oie->oie_dirent          = NULL;
5177         if (unlikely(!info->oti_it_ea_buf_used)) {
5178                 oie->oie_buf = info->oti_it_ea_buf;
5179                 info->oti_it_ea_buf_used = 1;
5180         } else {
5181                 OBD_ALLOC(oie->oie_buf, OSD_IT_EA_BUFSIZE);
5182                 if (oie->oie_buf == NULL)
5183                         RETURN(ERR_PTR(-ENOMEM));
5184         }
5185         oie->oie_obj             = obj;
5186
5187         file = &oie->oie_file;
5188
5189         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
5190         if (attr & LUDA_64BITHASH)
5191                 file->f_mode    = FMODE_64BITHASH;
5192         else
5193                 file->f_mode    = FMODE_32BITHASH;
5194         file->f_path.dentry     = obj_dentry;
5195         file->f_mapping         = obj->oo_inode->i_mapping;
5196         file->f_op              = obj->oo_inode->i_fop;
5197         set_file_inode(file, obj->oo_inode);
5198
5199         lu_object_get(lo);
5200         RETURN((struct dt_it *) oie);
5201 }
5202
5203 /**
5204  * Destroy or finishes iterator context.
5205  *
5206  * \param di iterator structure to be destroyed
5207  */
5208 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
5209 {
5210         struct osd_thread_info  *info = osd_oti_get(env);
5211         struct osd_it_ea        *oie    = (struct osd_it_ea *)di;
5212         struct osd_object       *obj    = oie->oie_obj;
5213         struct inode            *inode  = obj->oo_inode;
5214
5215         ENTRY;
5216         oie->oie_file.f_op->release(inode, &oie->oie_file);
5217         lu_object_put(env, &obj->oo_dt.do_lu);
5218         if (unlikely(oie->oie_buf != info->oti_it_ea_buf))
5219                 OBD_FREE(oie->oie_buf, OSD_IT_EA_BUFSIZE);
5220         else
5221                 info->oti_it_ea_buf_used = 0;
5222         OBD_SLAB_FREE_PTR(oie, osd_itea_cachep);
5223         EXIT;
5224 }
5225
5226 /**
5227  * It position the iterator at given key, so that next lookup continues from
5228  * that key Or it is similar to dio_it->load() but based on a key,
5229  * rather than file position.
5230  *
5231  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
5232  * to the beginning.
5233  *
5234  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
5235  */
5236 static int osd_it_ea_get(const struct lu_env *env,
5237                          struct dt_it *di, const struct dt_key *key)
5238 {
5239         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
5240
5241         ENTRY;
5242         LASSERT(((const char *)key)[0] == '\0');
5243         it->oie_file.f_pos      = 0;
5244         it->oie_rd_dirent       = 0;
5245         it->oie_it_dirent       = 0;
5246         it->oie_dirent          = NULL;
5247
5248         RETURN(+1);
5249 }
5250
5251 /**
5252  * Does nothing
5253  */
5254 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
5255 {
5256 }
5257
5258 struct osd_filldir_cbs {
5259 #ifdef HAVE_DIR_CONTEXT
5260         struct dir_context ctx;
5261 #endif
5262         struct osd_it_ea  *it;
5263 };
5264 /**
5265  * It is called internally by ->readdir(). It fills the
5266  * iterator's in-memory data structure with required
5267  * information i.e. name, namelen, rec_size etc.
5268  *
5269  * \param buf in which information to be filled in.
5270  * \param name name of the file in given dir
5271  *
5272  * \retval 0 on success
5273  * \retval 1 on buffer full
5274  */
5275 #ifdef HAVE_FILLDIR_USE_CTX
5276 static int osd_ldiskfs_filldir(struct dir_context  *buf,
5277                                const char *name, int namelen,
5278 #else
5279 static int osd_ldiskfs_filldir(void *buf, const char *name, int namelen,
5280 #endif
5281                                loff_t offset, __u64 ino,
5282                                unsigned d_type)
5283 {
5284         struct osd_it_ea        *it   =
5285                 ((struct osd_filldir_cbs *)buf)->it;
5286         struct osd_object       *obj  = it->oie_obj;
5287         struct osd_it_ea_dirent *ent  = it->oie_dirent;
5288         struct lu_fid           *fid  = &ent->oied_fid;
5289         struct osd_fid_pack     *rec;
5290         ENTRY;
5291
5292         /* this should never happen */
5293         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
5294                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
5295                 RETURN(-EIO);
5296         }
5297
5298         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
5299             OSD_IT_EA_BUFSIZE)
5300                 RETURN(1);
5301
5302         /* "." is just the object itself. */
5303         if (namelen == 1 && name[0] == '.') {
5304                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
5305         } else if (d_type & LDISKFS_DIRENT_LUFID) {
5306                 rec = (struct osd_fid_pack*) (name + namelen + 1);
5307                 if (osd_fid_unpack(fid, rec) != 0)
5308                         fid_zero(fid);
5309         } else {
5310                 fid_zero(fid);
5311         }
5312         d_type &= ~LDISKFS_DIRENT_LUFID;
5313
5314         /* NOT export local root. */
5315         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
5316                 ino = obj->oo_inode->i_ino;
5317                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
5318         }
5319
5320         ent->oied_ino     = ino;
5321         ent->oied_off     = offset;
5322         ent->oied_namelen = namelen;
5323         ent->oied_type    = d_type;
5324
5325         memcpy(ent->oied_name, name, namelen);
5326
5327         it->oie_rd_dirent++;
5328         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
5329         RETURN(0);
5330 }
5331
5332 /**
5333  * Calls ->readdir() to load a directory entry at a time
5334  * and stored it in iterator's in-memory data structure.
5335  *
5336  * \param di iterator's in memory structure
5337  *
5338  * \retval   0 on success
5339  * \retval -ve on error
5340  * \retval +1 reach the end of entry
5341  */
5342 static int osd_ldiskfs_it_fill(const struct lu_env *env,
5343                                const struct dt_it *di)
5344 {
5345         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
5346         struct osd_object  *obj   = it->oie_obj;
5347         struct inode       *inode = obj->oo_inode;
5348         struct htree_lock  *hlock = NULL;
5349         struct file        *filp  = &it->oie_file;
5350         int                 rc = 0;
5351         struct osd_filldir_cbs buf = {
5352 #ifdef HAVE_DIR_CONTEXT
5353                 .ctx.actor = osd_ldiskfs_filldir,
5354 #endif
5355                 .it = it
5356         };
5357
5358         ENTRY;
5359         it->oie_dirent = it->oie_buf;
5360         it->oie_rd_dirent = 0;
5361
5362         if (obj->oo_hl_head != NULL) {
5363                 hlock = osd_oti_get(env)->oti_hlock;
5364                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
5365                                    inode, LDISKFS_HLOCK_READDIR);
5366         } else {
5367                 down_read(&obj->oo_ext_idx_sem);
5368         }
5369
5370 #ifdef HAVE_DIR_CONTEXT
5371         buf.ctx.pos = filp->f_pos;
5372         rc = inode->i_fop->iterate(filp, &buf.ctx);
5373         filp->f_pos = buf.ctx.pos;
5374 #else
5375         rc = inode->i_fop->readdir(filp, &buf, osd_ldiskfs_filldir);
5376 #endif
5377
5378         if (hlock != NULL)
5379                 ldiskfs_htree_unlock(hlock);
5380         else
5381                 up_read(&obj->oo_ext_idx_sem);
5382
5383         if (it->oie_rd_dirent == 0) {
5384                 /*If it does not get any dirent, it means it has been reached
5385                  *to the end of the dir */
5386                 it->oie_file.f_pos = ldiskfs_get_htree_eof(&it->oie_file);
5387                 if (rc == 0)
5388                         rc = 1;
5389         } else {
5390                 it->oie_dirent = it->oie_buf;
5391                 it->oie_it_dirent = 1;
5392         }
5393
5394         RETURN(rc);
5395 }
5396
5397 /**
5398  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5399  * to load a directory entry at a time and stored it in
5400  * iterator's in-memory data structure.
5401  *
5402  * \param di iterator's in memory structure
5403  *
5404  * \retval +ve iterator reached to end
5405  * \retval   0 iterator not reached to end
5406  * \retval -ve on error
5407  */
5408 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
5409 {
5410         struct osd_it_ea *it = (struct osd_it_ea *)di;
5411         int rc;
5412
5413         ENTRY;
5414
5415         if (it->oie_it_dirent < it->oie_rd_dirent) {
5416                 it->oie_dirent =
5417                         (void *) it->oie_dirent +
5418                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
5419                                        it->oie_dirent->oied_namelen);
5420                 it->oie_it_dirent++;
5421                 RETURN(0);
5422         } else {
5423                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
5424                         rc = +1;
5425                 else
5426                         rc = osd_ldiskfs_it_fill(env, di);
5427         }
5428
5429         RETURN(rc);
5430 }
5431
5432 /**
5433  * Returns the key at current position from iterator's in memory structure.
5434  *
5435  * \param di iterator's in memory structure
5436  *
5437  * \retval key i.e. struct dt_key on success
5438  */
5439 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
5440                                     const struct dt_it *di)
5441 {
5442         struct osd_it_ea *it = (struct osd_it_ea *)di;
5443
5444         return (struct dt_key *)it->oie_dirent->oied_name;
5445 }
5446
5447 /**
5448  * Returns the key's size at current position from iterator's in memory structure.
5449  *
5450  * \param di iterator's in memory structure
5451  *
5452  * \retval key_size i.e. struct dt_key on success
5453  */
5454 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
5455 {
5456         struct osd_it_ea *it = (struct osd_it_ea *)di;
5457
5458         return it->oie_dirent->oied_namelen;
5459 }
5460
5461 static inline bool
5462 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
5463 {
5464         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
5465                  "dot_dotdot = %d\n", dot_dotdot);
5466
5467         if (LDISKFS_DIR_REC_LEN(de) >=
5468             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
5469                 return true;
5470
5471         return false;
5472 }
5473
5474 static inline bool
5475 osd_dirent_has_space(struct ldiskfs_dir_entry_2 *de, __u16 namelen,
5476                      unsigned blocksize, int dot_dotdot)
5477 {
5478         if (dot_dotdot > 0)
5479                 return osd_dot_dotdot_has_space(de, dot_dotdot);
5480
5481         if (ldiskfs_rec_len_from_disk(de->rec_len, blocksize) >=
5482             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
5483                 return true;
5484
5485         return false;
5486 }
5487
5488 static int
5489 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
5490                     struct dentry *dentry, const struct lu_fid *fid,
5491                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
5492                     struct htree_lock *hlock, int dot_dotdot)
5493 {
5494         struct inode                *dir        = dentry->d_parent->d_inode;
5495         struct inode                *inode      = dentry->d_inode;
5496         struct osd_fid_pack         *rec;
5497         struct ldiskfs_dentry_param *ldp;
5498         int                          namelen    = dentry->d_name.len;
5499         int                          rc;
5500         struct osd_thread_info     *info        = osd_oti_get(env);
5501         ENTRY;
5502
5503         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
5504                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
5505                 RETURN(0);
5506
5507         /* There is enough space to hold the FID-in-dirent. */
5508         if (osd_dirent_has_space(de, namelen, dir->i_sb->s_blocksize,
5509                                  dot_dotdot)) {
5510                 rc = ldiskfs_journal_get_write_access(jh, bh);
5511                 if (rc != 0)
5512                         RETURN(rc);
5513
5514                 de->name[namelen] = 0;
5515                 rec = (struct osd_fid_pack *)(de->name + namelen + 1);
5516                 rec->fp_len = sizeof(struct lu_fid) + 1;
5517                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
5518                 de->file_type |= LDISKFS_DIRENT_LUFID;
5519                 rc = ldiskfs_handle_dirty_metadata(jh, NULL, bh);
5520
5521                 RETURN(rc);
5522         }
5523
5524         LASSERTF(dot_dotdot == 0, "dot_dotdot = %d\n", dot_dotdot);
5525
5526         rc = ldiskfs_delete_entry(jh, dir, de, bh);
5527         if (rc != 0)
5528                 RETURN(rc);
5529
5530         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
5531         osd_get_ldiskfs_dirent_param(ldp, fid);
5532         dentry->d_fsdata = (void *)ldp;
5533         ll_vfs_dq_init(dir);
5534         rc = osd_ldiskfs_add_entry(info, jh, dentry, inode, hlock);
5535         /* It is too bad, we cannot reinsert the name entry back.
5536          * That means we lose it! */
5537         if (rc != 0)
5538                 CDEBUG(D_LFSCK, "%.16s: fail to reinsert the dirent, "
5539                        "dir = %lu/%u, name = %.*s, "DFID": rc = %d\n",
5540                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
5541                        dir->i_ino, dir->i_generation, namelen,
5542                        dentry->d_name.name, PFID(fid), rc);
5543
5544         RETURN(rc);
5545 }
5546
5547 static int
5548 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
5549                         struct osd_it_ea *it, struct lu_fid *fid,
5550                         struct osd_inode_id *id, __u32 *attr)
5551 {
5552         struct osd_thread_info     *info        = osd_oti_get(env);
5553         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
5554         struct osd_device          *dev         = osd_obj2dev(obj);
5555         struct super_block         *sb          = osd_sb(dev);
5556         const char                 *devname     =
5557                                         LDISKFS_SB(sb)->s_es->s_volume_name;
5558         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
5559         struct inode               *dir         = obj->oo_inode;
5560         struct htree_lock          *hlock       = NULL;
5561         struct buffer_head         *bh          = NULL;
5562         handle_t                   *jh          = NULL;
5563         struct ldiskfs_dir_entry_2 *de;
5564         struct dentry              *dentry;
5565         struct inode               *inode;
5566         int                         credits;
5567         int                         rc;
5568         int                         dot_dotdot  = 0;
5569         bool                        dirty       = false;
5570         ENTRY;
5571
5572         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
5573         inode = osd_iget(info, dev, id);
5574         if (IS_ERR(inode)) {
5575                 rc = PTR_ERR(inode);
5576                 if (rc == -ENOENT || rc == -ESTALE) {
5577                         *attr |= LUDA_UNKNOWN;
5578                         rc = 0;
5579                 } else {
5580                         CDEBUG(D_LFSCK, "%.16s: fail to iget for dirent "
5581                                "check_repair, dir = %lu/%u, name = %.*s: "
5582                                "rc = %d\n",
5583                                devname, dir->i_ino, dir->i_generation,
5584                                ent->oied_namelen, ent->oied_name, rc);
5585                 }
5586
5587                 RETURN(rc);
5588         }
5589
5590         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
5591                                            ent->oied_namelen);
5592         rc = osd_get_lma(info, inode, dentry, lma);
5593         if (rc == -ENODATA)
5594                 lma = NULL;
5595         else if (rc != 0)
5596                 GOTO(out, rc);
5597
5598         if (ent->oied_name[0] == '.') {
5599                 if (ent->oied_namelen == 1)
5600                         dot_dotdot = 1;
5601                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
5602                         dot_dotdot = 2;
5603         }
5604
5605         /* We need to ensure that the name entry is still valid.
5606          * Because it may be removed or renamed by other already.
5607          *
5608          * The unlink or rename operation will start journal before PDO lock,
5609          * so to avoid deadlock, here we need to start journal handle before
5610          * related PDO lock also. But because we do not know whether there
5611          * will be something to be repaired before PDO lock, we just start
5612          * journal without conditions.
5613          *
5614          * We may need to remove the name entry firstly, then insert back.
5615          * One credit is for user quota file update.
5616          * One credit is for group quota file update.
5617          * Two credits are for dirty inode. */
5618         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
5619                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
5620
5621         if (dev->od_dirent_journal != 0) {
5622
5623 again:
5624                 jh = osd_journal_start_sb(sb, LDISKFS_HT_MISC, credits);
5625                 if (IS_ERR(jh)) {
5626                         rc = PTR_ERR(jh);
5627                         CDEBUG(D_LFSCK, "%.16s: fail to start trans for dirent "
5628                                "check_repair, dir = %lu/%u, credits = %d, "
5629                                "name = %.*s: rc = %d\n",
5630                                devname, dir->i_ino, dir->i_generation, credits,
5631                                ent->oied_namelen, ent->oied_name, rc);
5632
5633                         GOTO(out_inode, rc);
5634                 }
5635
5636                 if (obj->oo_hl_head != NULL) {
5637                         hlock = osd_oti_get(env)->oti_hlock;
5638                         /* "0" means exclusive lock for the whole directory.
5639                          * We need to prevent others access such name entry
5640                          * during the delete + insert. Neither HLOCK_ADD nor
5641                          * HLOCK_DEL cannot guarantee the atomicity. */
5642                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
5643                 } else {
5644                         down_write(&obj->oo_ext_idx_sem);
5645                 }
5646         } else {
5647                 if (obj->oo_hl_head != NULL) {
5648                         hlock = osd_oti_get(env)->oti_hlock;
5649                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
5650                                            LDISKFS_HLOCK_LOOKUP);
5651                 } else {
5652                         down_read(&obj->oo_ext_idx_sem);
5653                 }
5654         }
5655
5656         bh = osd_ldiskfs_find_entry(dir, &dentry->d_name, &de, NULL, hlock);
5657         /* For dot/dotdot entry, if there is not enough space to hold the
5658          * FID-in-dirent, just keep them there. It only happens when the
5659          * device upgraded from 1.8 or restored from MDT file-level backup.
5660          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
5661          * and needs to get FID from LMA when readdir, it will not affect the
5662          * performance much. */
5663         if ((bh == NULL) || (le32_to_cpu(de->inode) != inode->i_ino) ||
5664             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
5665                 *attr |= LUDA_IGNORE;
5666
5667                 GOTO(out, rc = 0);
5668         }
5669
5670         if (lma != NULL) {
5671                 if (unlikely(lma->lma_compat & LMAC_NOT_IN_OI)) {
5672                         struct lu_fid *tfid = &lma->lma_self_fid;
5673
5674                         *attr |= LUDA_IGNORE;
5675                         /* It must be REMOTE_PARENT_DIR and as the
5676                          * dotdot entry of remote directory */
5677                         if (unlikely(dot_dotdot != 2 ||
5678                                      fid_seq(tfid) != FID_SEQ_LOCAL_FILE ||
5679                                      fid_oid(tfid) != REMOTE_PARENT_DIR_OID)) {
5680                                 CDEBUG(D_LFSCK, "%.16s: expect remote agent "
5681                                        "parent directory, but got %.*s under "
5682                                        "dir = %lu/%u with the FID "DFID"\n",
5683                                        devname, ent->oied_namelen,
5684                                        ent->oied_name, dir->i_ino,
5685                                        dir->i_generation, PFID(tfid));
5686
5687                                 GOTO(out, rc = -EIO);
5688                         }
5689
5690                         GOTO(out, rc = 0);
5691                 }
5692
5693                 if (fid_is_sane(fid)) {
5694                         /* FID-in-dirent is valid. */
5695                         if (lu_fid_eq(fid, &lma->lma_self_fid))
5696                                 GOTO(out, rc = 0);
5697
5698                         /* Do not repair under dryrun mode. */
5699                         if (*attr & LUDA_VERIFY_DRYRUN) {
5700                                 *attr |= LUDA_REPAIR;
5701
5702                                 GOTO(out, rc = 0);
5703                         }
5704
5705                         if (jh == NULL) {
5706                                 brelse(bh);
5707                                 dev->od_dirent_journal = 1;
5708                                 if (hlock != NULL) {
5709                                         ldiskfs_htree_unlock(hlock);
5710                                         hlock = NULL;
5711                                 } else {
5712                                         up_read(&obj->oo_ext_idx_sem);
5713                                 }
5714
5715                                 goto again;
5716                         }
5717
5718                         *fid = lma->lma_self_fid;
5719                         dirty = true;
5720                         /* Update the FID-in-dirent. */
5721                         rc = osd_dirent_reinsert(env, jh, dentry, fid, bh, de,
5722                                                  hlock, dot_dotdot);
5723                         if (rc == 0)
5724                                 *attr |= LUDA_REPAIR;
5725                         else
5726                                 CDEBUG(D_LFSCK, "%.16s: fail to update FID "
5727                                        "in the dirent, dir = %lu/%u, "
5728                                        "name = %.*s, "DFID": rc = %d\n",
5729                                        devname, dir->i_ino, dir->i_generation,
5730                                        ent->oied_namelen, ent->oied_name,
5731                                        PFID(fid), rc);
5732                 } else {
5733                         /* Do not repair under dryrun mode. */
5734                         if (*attr & LUDA_VERIFY_DRYRUN) {
5735                                 *fid = lma->lma_self_fid;
5736                                 *attr |= LUDA_REPAIR;
5737
5738                                 GOTO(out, rc = 0);
5739                         }
5740
5741                         if (jh == NULL) {
5742                                 brelse(bh);
5743                                 dev->od_dirent_journal = 1;
5744                                 if (hlock != NULL) {
5745                                         ldiskfs_htree_unlock(hlock);
5746                                         hlock = NULL;
5747                                 } else {
5748                                         up_read(&obj->oo_ext_idx_sem);
5749                                 }
5750
5751                                 goto again;
5752                         }
5753
5754                         *fid = lma->lma_self_fid;
5755                         dirty = true;
5756                         /* Append the FID-in-dirent. */
5757                         rc = osd_dirent_reinsert(env, jh, dentry, fid, bh, de,
5758                                                  hlock, dot_dotdot);
5759                         if (rc == 0)
5760                                 *attr |= LUDA_REPAIR;
5761                         else
5762                                 CDEBUG(D_LFSCK, "%.16s: fail to append FID "
5763                                        "after the dirent, dir = %lu/%u, "
5764                                        "name = %.*s, "DFID": rc = %d\n",
5765                                        devname, dir->i_ino, dir->i_generation,
5766                                        ent->oied_namelen, ent->oied_name,
5767                                        PFID(fid), rc);
5768                 }
5769         } else {
5770                 /* Do not repair under dryrun mode. */
5771                 if (*attr & LUDA_VERIFY_DRYRUN) {
5772                         if (fid_is_sane(fid)) {
5773                                 *attr |= LUDA_REPAIR;
5774                         } else {
5775                                 lu_igif_build(fid, inode->i_ino,
5776                                               inode->i_generation);
5777                                 *attr |= LUDA_UPGRADE;
5778                         }
5779
5780                         GOTO(out, rc = 0);
5781                 }
5782
5783                 if (jh == NULL) {
5784                         brelse(bh);
5785                         dev->od_dirent_journal = 1;
5786                         if (hlock != NULL) {
5787                                 ldiskfs_htree_unlock(hlock);
5788                                 hlock = NULL;
5789                         } else {
5790                                 up_read(&obj->oo_ext_idx_sem);
5791                         }
5792
5793                         goto again;
5794                 }
5795
5796                 dirty = true;
5797                 if (unlikely(fid_is_sane(fid))) {
5798                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5799                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5800                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5801                         if (rc == 0)
5802                                 *attr |= LUDA_REPAIR;
5803                         else
5804                                 CDEBUG(D_LFSCK, "%.16s: fail to set LMA for "
5805                                        "update dirent, dir = %lu/%u, "
5806                                        "name = %.*s, "DFID": rc = %d\n",
5807                                        devname, dir->i_ino, dir->i_generation,
5808                                        ent->oied_namelen, ent->oied_name,
5809                                        PFID(fid), rc);
5810                 } else {
5811                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5812                         /* It is probably IGIF object. Only aappend the
5813                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5814                         rc = osd_dirent_reinsert(env, jh, dentry, fid, bh, de,
5815                                                  hlock, dot_dotdot);
5816                         if (rc == 0)
5817                                 *attr |= LUDA_UPGRADE;
5818                         else
5819                                 CDEBUG(D_LFSCK, "%.16s: fail to append IGIF "
5820                                        "after the dirent, dir = %lu/%u, "
5821                                        "name = %.*s, "DFID": rc = %d\n",
5822                                        devname, dir->i_ino, dir->i_generation,
5823                                        ent->oied_namelen, ent->oied_name,
5824                                        PFID(fid), rc);
5825                 }
5826         }
5827
5828         GOTO(out, rc);
5829
5830 out:
5831         brelse(bh);
5832         if (hlock != NULL) {
5833                 ldiskfs_htree_unlock(hlock);
5834         } else {
5835                 if (dev->od_dirent_journal != 0)
5836                         up_write(&obj->oo_ext_idx_sem);
5837                 else
5838                         up_read(&obj->oo_ext_idx_sem);
5839         }
5840
5841         if (jh != NULL)
5842                 ldiskfs_journal_stop(jh);
5843
5844 out_inode:
5845         iput(inode);
5846         if (rc >= 0 && !dirty)
5847                 dev->od_dirent_journal = 0;
5848
5849         return rc;
5850 }
5851
5852 /**
5853  * Returns the value at current position from iterator's in memory structure.
5854  *
5855  * \param di struct osd_it_ea, iterator's in memory structure
5856  * \param attr attr requested for dirent.
5857  * \param lde lustre dirent
5858  *
5859  * \retval   0 no error and \param lde has correct lustre dirent.
5860  * \retval -ve on error
5861  */
5862 static inline int osd_it_ea_rec(const struct lu_env *env,
5863                                 const struct dt_it *di,
5864                                 struct dt_rec *dtrec, __u32 attr)
5865 {
5866         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5867         struct osd_object      *obj   = it->oie_obj;
5868         struct osd_device      *dev   = osd_obj2dev(obj);
5869         struct osd_thread_info *oti   = osd_oti_get(env);
5870         struct osd_inode_id    *id    = &oti->oti_id;
5871         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5872         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5873         __u32                   ino   = it->oie_dirent->oied_ino;
5874         int                     rc    = 0;
5875         ENTRY;
5876
5877         LASSERT(obj->oo_inode != dev->od_mdt_map->omm_remote_parent->d_inode);
5878
5879         if (attr & LUDA_VERIFY) {
5880                 if (unlikely(ino == osd_remote_parent_ino(dev))) {
5881                         attr |= LUDA_IGNORE;
5882                         /* If the parent is on remote MDT, and there
5883                          * is no FID-in-dirent, then we have to get
5884                          * the parent FID from the linkEA.  */
5885                         if (!fid_is_sane(fid) &&
5886                             it->oie_dirent->oied_namelen == 2 &&
5887                             it->oie_dirent->oied_name[0] == '.' &&
5888                             it->oie_dirent->oied_name[1] == '.')
5889                                 osd_get_pfid_from_linkea(env, obj, fid);
5890                 } else {
5891                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5892                                                      &attr);
5893                 }
5894
5895                 if (!fid_is_sane(fid)) {
5896                         attr &= ~LUDA_IGNORE;
5897                         attr |= LUDA_UNKNOWN;
5898                 }
5899         } else {
5900                 attr &= ~LU_DIRENT_ATTRS_MASK;
5901                 if (!fid_is_sane(fid)) {
5902                         bool is_dotdot = false;
5903                         if (it->oie_dirent->oied_namelen == 2 &&
5904                             it->oie_dirent->oied_name[0] == '.' &&
5905                             it->oie_dirent->oied_name[1] == '.')
5906                                 is_dotdot = true;
5907                         /* If the parent is on remote MDT, and there
5908                          * is no FID-in-dirent, then we have to get
5909                          * the parent FID from the linkEA.  */
5910                         if (ino == osd_remote_parent_ino(dev) && is_dotdot) {
5911                                 rc = osd_get_pfid_from_linkea(env, obj, fid);
5912                         } else {
5913                                 if (is_dotdot == false &&
5914                                     OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5915                                         RETURN(-ENOENT);
5916
5917                                 rc = osd_ea_fid_get(env, obj, ino, fid, id);
5918                         }
5919                 } else {
5920                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5921                 }
5922         }
5923
5924         /* Pack the entry anyway, at least the offset is right. */
5925         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5926                            it->oie_dirent->oied_name,
5927                            it->oie_dirent->oied_namelen,
5928                            it->oie_dirent->oied_type, attr);
5929
5930         if (rc < 0)
5931                 RETURN(rc);
5932
5933         if (osd_remote_fid(env, dev, fid))
5934                 RETURN(0);
5935
5936         if (likely(!(attr & (LUDA_IGNORE | LUDA_UNKNOWN)) && rc == 0))
5937                 osd_add_oi_cache(oti, dev, id, fid);
5938
5939         RETURN(rc > 0 ? 0 : rc);
5940 }
5941
5942 /**
5943  * Returns the record size size at current position.
5944  *
5945  * This function will return record(lu_dirent) size in bytes.
5946  *
5947  * \param[in] env       execution environment
5948  * \param[in] di        iterator's in memory structure
5949  * \param[in] attr      attribute of the entry, only requires LUDA_TYPE to
5950  *                      calculate the lu_dirent size.
5951  *
5952  * \retval      record size(in bytes & in memory) of the current lu_dirent
5953  *              entry.
5954  */
5955 static int osd_it_ea_rec_size(const struct lu_env *env, const struct dt_it *di,
5956                               __u32 attr)
5957 {
5958         struct osd_it_ea *it = (struct osd_it_ea *)di;
5959
5960         return lu_dirent_calc_size(it->oie_dirent->oied_namelen, attr);
5961 }
5962
5963 /**
5964  * Returns a cookie for current position of the iterator head, so that
5965  * user can use this cookie to load/start the iterator next time.
5966  *
5967  * \param di iterator's in memory structure
5968  *
5969  * \retval cookie for current position, on success
5970  */
5971 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5972 {
5973         struct osd_it_ea *it = (struct osd_it_ea *)di;
5974
5975         return it->oie_dirent->oied_off;
5976 }
5977
5978 /**
5979  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5980  * to load a directory entry at a time and stored it i inn,
5981  * in iterator's in-memory data structure.
5982  *
5983  * \param di struct osd_it_ea, iterator's in memory structure
5984  *
5985  * \retval +ve on success
5986  * \retval -ve on error
5987  */
5988 static int osd_it_ea_load(const struct lu_env *env,
5989                           const struct dt_it *di, __u64 hash)
5990 {
5991         struct osd_it_ea *it = (struct osd_it_ea *)di;
5992         int rc;
5993
5994         ENTRY;
5995         it->oie_file.f_pos = hash;
5996
5997         rc =  osd_ldiskfs_it_fill(env, di);
5998         if (rc > 0)
5999                 rc = -ENODATA;
6000
6001         if (rc == 0)
6002                 rc = +1;
6003
6004         RETURN(rc);
6005 }
6006
6007 /**
6008  * Index lookup function for interoperability mode (b11826).
6009  *
6010  * \param key,  key i.e. file name to be searched
6011  *
6012  * \retval +ve, on success
6013  * \retval -ve, on error
6014  */
6015 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
6016                                struct dt_rec *rec, const struct dt_key *key)
6017 {
6018         struct osd_object *obj = osd_dt_obj(dt);
6019         int rc = 0;
6020
6021         ENTRY;
6022
6023         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
6024         LINVRNT(osd_invariant(obj));
6025
6026         rc = osd_ea_lookup_rec(env, obj, rec, key);
6027         if (rc == 0)
6028                 rc = +1;
6029         RETURN(rc);
6030 }
6031
6032 /**
6033  * Index and Iterator operations for interoperability
6034  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
6035  */
6036 static const struct dt_index_operations osd_index_ea_ops = {
6037         .dio_lookup         = osd_index_ea_lookup,
6038         .dio_declare_insert = osd_index_declare_ea_insert,
6039         .dio_insert         = osd_index_ea_insert,
6040         .dio_declare_delete = osd_index_declare_ea_delete,
6041         .dio_delete         = osd_index_ea_delete,
6042         .dio_it     = {
6043                 .init     = osd_it_ea_init,
6044                 .fini     = osd_it_ea_fini,
6045                 .get      = osd_it_ea_get,
6046                 .put      = osd_it_ea_put,
6047                 .next     = osd_it_ea_next,
6048                 .key      = osd_it_ea_key,
6049                 .key_size = osd_it_ea_key_size,
6050                 .rec      = osd_it_ea_rec,
6051                 .rec_size = osd_it_ea_rec_size,
6052                 .store    = osd_it_ea_store,
6053                 .load     = osd_it_ea_load
6054         }
6055 };
6056
6057 static void *osd_key_init(const struct lu_context *ctx,
6058                           struct lu_context_key *key)
6059 {
6060         struct osd_thread_info *info;
6061
6062         OBD_ALLOC_PTR(info);
6063         if (info == NULL)
6064                 return ERR_PTR(-ENOMEM);
6065
6066         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6067         if (info->oti_it_ea_buf == NULL)
6068                 goto out_free_info;
6069
6070         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
6071
6072         info->oti_hlock = ldiskfs_htree_lock_alloc();
6073         if (info->oti_hlock == NULL)
6074                 goto out_free_ea;
6075
6076         return info;
6077
6078  out_free_ea:
6079         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6080  out_free_info:
6081         OBD_FREE_PTR(info);
6082         return ERR_PTR(-ENOMEM);
6083 }
6084
6085 static void osd_key_fini(const struct lu_context *ctx,
6086                          struct lu_context_key *key, void* data)
6087 {
6088         struct osd_thread_info *info = data;
6089         struct ldiskfs_inode_info *lli = LDISKFS_I(info->oti_inode);
6090         struct osd_idmap_cache  *idc = info->oti_ins_cache;
6091
6092         if (info->oti_inode != NULL)
6093                 OBD_FREE_PTR(lli);
6094         if (info->oti_hlock != NULL)
6095                 ldiskfs_htree_lock_free(info->oti_hlock);
6096         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
6097         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
6098         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
6099         lu_buf_free(&info->oti_big_buf);
6100         if (idc != NULL) {
6101                 LASSERT(info->oti_ins_cache_size > 0);
6102                 OBD_FREE(idc, sizeof(*idc) * info->oti_ins_cache_size);
6103                 info->oti_ins_cache = NULL;
6104                 info->oti_ins_cache_size = 0;
6105         }
6106         OBD_FREE_PTR(info);
6107 }
6108
6109 static void osd_key_exit(const struct lu_context *ctx,
6110                          struct lu_context_key *key, void *data)
6111 {
6112         struct osd_thread_info *info = data;
6113
6114         LASSERT(info->oti_r_locks == 0);
6115         LASSERT(info->oti_w_locks == 0);
6116         LASSERT(info->oti_txns    == 0);
6117 }
6118
6119 /* type constructor/destructor: osd_type_init, osd_type_fini */
6120 LU_TYPE_INIT_FINI(osd, &osd_key);
6121
6122 struct lu_context_key osd_key = {
6123         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
6124         .lct_init = osd_key_init,
6125         .lct_fini = osd_key_fini,
6126         .lct_exit = osd_key_exit
6127 };
6128
6129
6130 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
6131                            const char *name, struct lu_device *next)
6132 {
6133         struct osd_device *osd = osd_dev(d);
6134
6135         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
6136             >= sizeof(osd->od_svname))
6137                 return -E2BIG;
6138         return osd_procfs_init(osd, name);
6139 }
6140
6141 static int osd_fid_init(const struct lu_env *env, struct osd_device *osd)
6142 {
6143         struct seq_server_site  *ss = osd_seq_site(osd);
6144         int                     rc;
6145         ENTRY;
6146
6147         if (osd->od_is_ost || osd->od_cl_seq != NULL)
6148                 RETURN(0);
6149
6150         if (unlikely(ss == NULL))
6151                 RETURN(-ENODEV);
6152
6153         OBD_ALLOC_PTR(osd->od_cl_seq);
6154         if (osd->od_cl_seq == NULL)
6155                 RETURN(-ENOMEM);
6156
6157         rc = seq_client_init(osd->od_cl_seq, NULL, LUSTRE_SEQ_METADATA,
6158                              osd->od_svname, ss->ss_server_seq);
6159         if (rc != 0) {
6160                 OBD_FREE_PTR(osd->od_cl_seq);
6161                 osd->od_cl_seq = NULL;
6162                 RETURN(rc);
6163         }
6164
6165         if (ss->ss_node_id == 0) {
6166                 /* If the OSD on the sequence controller(MDT0), then allocate
6167                  * sequence here, otherwise allocate sequence after connected
6168                  * to MDT0 (see mdt_register_lwp_callback()). */
6169                 rc = seq_server_alloc_meta(osd->od_cl_seq->lcs_srv,
6170                                    &osd->od_cl_seq->lcs_space, env);
6171         }
6172
6173         RETURN(rc);
6174 }
6175
6176 static void osd_fid_fini(const struct lu_env *env, struct osd_device *osd)
6177 {
6178         if (osd->od_cl_seq == NULL)
6179                 return;
6180
6181         seq_client_fini(osd->od_cl_seq);
6182         OBD_FREE_PTR(osd->od_cl_seq);
6183         osd->od_cl_seq = NULL;
6184 }
6185
6186 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
6187 {
6188         ENTRY;
6189
6190         /* shutdown quota slave instance associated with the device */
6191         if (o->od_quota_slave != NULL) {
6192                 qsd_fini(env, o->od_quota_slave);
6193                 o->od_quota_slave = NULL;
6194         }
6195
6196         osd_fid_fini(env, o);
6197
6198         RETURN(0);
6199 }
6200
6201 static void osd_umount(const struct lu_env *env, struct osd_device *o)
6202 {
6203         ENTRY;
6204
6205         if (o->od_mnt != NULL) {
6206                 shrink_dcache_sb(osd_sb(o));
6207                 osd_sync(env, &o->od_dt_dev);
6208
6209                 mntput(o->od_mnt);
6210                 o->od_mnt = NULL;
6211         }
6212
6213         EXIT;
6214 }
6215
6216 static int osd_mount(const struct lu_env *env,
6217                      struct osd_device *o, struct lustre_cfg *cfg)
6218 {
6219         const char              *name  = lustre_cfg_string(cfg, 0);
6220         const char              *dev  = lustre_cfg_string(cfg, 1);
6221         const char              *opts;
6222         unsigned long            page, s_flags, lmd_flags = 0;
6223         struct page             *__page;
6224         struct file_system_type *type;
6225         char                    *options = NULL;
6226         char                    *str;
6227         struct osd_thread_info  *info = osd_oti_get(env);
6228         struct lu_fid           *fid = &info->oti_fid;
6229         struct inode            *inode;
6230         int                      rc = 0, force_over_256tb = 0;
6231         ENTRY;
6232
6233         if (o->od_mnt != NULL)
6234                 RETURN(0);
6235
6236         if (strlen(dev) >= sizeof(o->od_mntdev))
6237                 RETURN(-E2BIG);
6238         strcpy(o->od_mntdev, dev);
6239
6240         str = lustre_cfg_string(cfg, 2);
6241         s_flags = simple_strtoul(str, NULL, 0);
6242         str = strstr(str, ":");
6243         if (str)
6244                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
6245         opts = lustre_cfg_string(cfg, 3);
6246 #ifdef __BIG_ENDIAN
6247         if (opts == NULL || strstr(opts, "bigendian_extents") == NULL) {
6248                 CERROR("%s: device %s extents feature is not guaranteed to "
6249                        "work on big-endian systems. Use \"bigendian_extents\" "
6250                        "mount option to override.\n", name, dev);
6251                 RETURN(-EINVAL);
6252         }
6253 #endif
6254         if (opts != NULL && strstr(opts, "force_over_128tb") != NULL) {
6255                 CWARN("force_over_128tb option is depricated."
6256                       "Filesystems less then 256TB can be created without any"
6257                       "force options. Use force_over_256tb option for"
6258                       "filesystems greather then 256TB.\n");
6259         }
6260
6261         if (opts != NULL && strstr(opts, "force_over_256tb") != NULL)
6262                 force_over_256tb = 1;
6263
6264         __page = alloc_page(GFP_KERNEL);
6265         if (__page == NULL)
6266                 GOTO(out, rc = -ENOMEM);
6267         page = (unsigned long)page_address(__page);
6268         options = (char *)page;
6269         *options = '\0';
6270         if (opts != NULL) {
6271                 /* strip out the options for back compatiblity */
6272                 static char *sout[] = {
6273                         "mballoc",
6274                         "iopen",
6275                         "noiopen",
6276                         "iopen_nopriv",
6277                         "extents",
6278                         "noextents",
6279                         /* strip out option we processed in osd */
6280                         "bigendian_extents",
6281 #if LUSTRE_VERSION_CODE >= OBD_OCD_VERSION(3,0,53,0)
6282 #warning "remove force_over_128 option"
6283 #else
6284                         "force_over_128tb (deprecated)",
6285 #endif
6286                         "force_over_256tb",
6287                         NULL
6288                 };
6289                 strcat(options, opts);
6290                 for (rc = 0, str = options; sout[rc]; ) {
6291                         char *op = strstr(str, sout[rc]);
6292                         if (op == NULL) {
6293                                 rc++;
6294                                 str = options;
6295                                 continue;
6296                         }
6297                         if (op == options || *(op - 1) == ',') {
6298                                 str = op + strlen(sout[rc]);
6299                                 if (*str == ',' || *str == '\0') {
6300                                         *str == ',' ? str++ : str;
6301                                         memmove(op, str, strlen(str) + 1);
6302                                 }
6303                         }
6304                         for (str = op; *str != ',' && *str != '\0'; str++)
6305                                 ;
6306                 }
6307         } else {
6308                 strncat(options, "user_xattr,acl", 14);
6309         }
6310
6311         /* Glom up mount options */
6312         if (*options != '\0')
6313                 strcat(options, ",");
6314         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
6315
6316         type = get_fs_type("ldiskfs");
6317         if (!type) {
6318                 CERROR("%s: cannot find ldiskfs module\n", name);
6319                 GOTO(out, rc = -ENODEV);
6320         }
6321
6322         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
6323         module_put(type->owner);
6324
6325         if (IS_ERR(o->od_mnt)) {
6326                 rc = PTR_ERR(o->od_mnt);
6327                 o->od_mnt = NULL;
6328                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
6329                 GOTO(out, rc);
6330         }
6331
6332         if (ldiskfs_blocks_count(LDISKFS_SB(osd_sb(o))->s_es) > (64ULL << 30) &&
6333             force_over_256tb == 0) {
6334                 CERROR("%s: device %s LDISKFS does not support filesystems "
6335                        "greater than 256TB and can cause data corruption. "
6336                        "Use \"force_over_256tb\" mount option to override.\n",
6337                        name, dev);
6338                 GOTO(out, rc = -EINVAL);
6339         }
6340
6341 #ifdef HAVE_DEV_SET_RDONLY
6342         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
6343                 CERROR("%s: underlying device %s is marked as read-only. "
6344                        "Setup failed\n", name, dev);
6345                 GOTO(out_mnt, rc = -EROFS);
6346         }
6347 #endif
6348
6349         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
6350                                         LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
6351                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
6352                 GOTO(out_mnt, rc = -EINVAL);
6353         }
6354
6355 #ifdef LDISKFS_MOUNT_DIRDATA
6356         if (LDISKFS_HAS_INCOMPAT_FEATURE(o->od_mnt->mnt_sb,
6357                                          LDISKFS_FEATURE_INCOMPAT_DIRDATA))
6358                 LDISKFS_SB(osd_sb(o))->s_mount_opt |= LDISKFS_MOUNT_DIRDATA;
6359         else if (!o->od_is_ost)
6360                 CWARN("%s: device %s was upgraded from Lustre-1.x without "
6361                       "enabling the dirdata feature. If you do not want to "
6362                       "downgrade to Lustre-1.x again, you can enable it via "
6363                       "'tune2fs -O dirdata device'\n", name, dev);
6364 #endif
6365         inode = osd_sb(o)->s_root->d_inode;
6366         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
6367         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
6368         if (rc != 0) {
6369                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
6370                 GOTO(out_mnt, rc);
6371         }
6372
6373         if (lmd_flags & LMD_FLG_NOSCRUB)
6374                 o->od_noscrub = 1;
6375
6376         GOTO(out, rc = 0);
6377
6378 out_mnt:
6379         mntput(o->od_mnt);
6380         o->od_mnt = NULL;
6381
6382 out:
6383         if (__page)
6384                 __free_page(__page);
6385
6386         return rc;
6387 }
6388
6389 static struct lu_device *osd_device_fini(const struct lu_env *env,
6390                                          struct lu_device *d)
6391 {
6392         struct osd_device *o = osd_dev(d);
6393         ENTRY;
6394
6395         osd_shutdown(env, o);
6396         osd_procfs_fini(o);
6397         osd_scrub_cleanup(env, o);
6398         osd_obj_map_fini(o);
6399         osd_umount(env, o);
6400
6401         RETURN(NULL);
6402 }
6403
6404 static int osd_device_init0(const struct lu_env *env,
6405                             struct osd_device *o,
6406                             struct lustre_cfg *cfg)
6407 {
6408         struct lu_device        *l = osd2lu_dev(o);
6409         struct osd_thread_info *info;
6410         int                     rc;
6411         int                     cplen = 0;
6412
6413         /* if the module was re-loaded, env can loose its keys */
6414         rc = lu_env_refill((struct lu_env *) env);
6415         if (rc)
6416                 GOTO(out, rc);
6417         info = osd_oti_get(env);
6418         LASSERT(info);
6419
6420         l->ld_ops = &osd_lu_ops;
6421         o->od_dt_dev.dd_ops = &osd_dt_ops;
6422
6423         spin_lock_init(&o->od_osfs_lock);
6424         mutex_init(&o->od_otable_mutex);
6425         INIT_LIST_HEAD(&o->od_orphan_list);
6426
6427         o->od_read_cache = 1;
6428         o->od_writethrough_cache = 1;
6429         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
6430
6431         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
6432                         sizeof(o->od_svname));
6433         if (cplen >= sizeof(o->od_svname)) {
6434                 rc = -E2BIG;
6435                 GOTO(out, rc);
6436         }
6437
6438         o->od_index = -1; /* -1 means index is invalid */
6439         rc = server_name2index(o->od_svname, &o->od_index, NULL);
6440         if (rc == LDD_F_SV_TYPE_OST)
6441                 o->od_is_ost = 1;
6442
6443         o->od_full_scrub_ratio = OFSR_DEFAULT;
6444         o->od_full_scrub_threshold_rate = FULL_SCRUB_THRESHOLD_RATE_DEFAULT;
6445         rc = osd_mount(env, o, cfg);
6446         if (rc != 0)
6447                 GOTO(out, rc);
6448
6449         rc = osd_obj_map_init(env, o);
6450         if (rc != 0)
6451                 GOTO(out_mnt, rc);
6452
6453         rc = lu_site_init(&o->od_site, l);
6454         if (rc != 0)
6455                 GOTO(out_compat, rc);
6456         o->od_site.ls_bottom_dev = l;
6457
6458         rc = lu_site_init_finish(&o->od_site);
6459         if (rc != 0)
6460                 GOTO(out_site, rc);
6461
6462         INIT_LIST_HEAD(&o->od_ios_list);
6463         /* setup scrub, including OI files initialization */
6464         rc = osd_scrub_setup(env, o);
6465         if (rc < 0)
6466                 GOTO(out_site, rc);
6467
6468         rc = osd_procfs_init(o, o->od_svname);
6469         if (rc != 0) {
6470                 CERROR("%s: can't initialize procfs: rc = %d\n",
6471                        o->od_svname, rc);
6472                 GOTO(out_scrub, rc);
6473         }
6474
6475         LASSERT(l->ld_site->ls_linkage.next != NULL);
6476         LASSERT(l->ld_site->ls_linkage.prev != NULL);
6477
6478         /* initialize quota slave instance */
6479         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
6480                                      o->od_proc_entry);
6481         if (IS_ERR(o->od_quota_slave)) {
6482                 rc = PTR_ERR(o->od_quota_slave);
6483                 o->od_quota_slave = NULL;
6484                 GOTO(out_procfs, rc);
6485         }
6486
6487         RETURN(0);
6488
6489 out_procfs:
6490         osd_procfs_fini(o);
6491 out_scrub:
6492         osd_scrub_cleanup(env, o);
6493 out_site:
6494         lu_site_fini(&o->od_site);
6495 out_compat:
6496         osd_obj_map_fini(o);
6497 out_mnt:
6498         osd_umount(env, o);
6499 out:
6500         return rc;
6501 }
6502
6503 static struct lu_device *osd_device_alloc(const struct lu_env *env,
6504                                           struct lu_device_type *t,
6505                                           struct lustre_cfg *cfg)
6506 {
6507         struct osd_device *o;
6508         int                rc;
6509
6510         OBD_ALLOC_PTR(o);
6511         if (o == NULL)
6512                 return ERR_PTR(-ENOMEM);
6513
6514         rc = dt_device_init(&o->od_dt_dev, t);
6515         if (rc == 0) {
6516                 /* Because the ctx might be revived in dt_device_init,
6517                  * refill the env here */
6518                 lu_env_refill((struct lu_env *)env);
6519                 rc = osd_device_init0(env, o, cfg);
6520                 if (rc)
6521                         dt_device_fini(&o->od_dt_dev);
6522         }
6523
6524         if (unlikely(rc != 0))
6525                 OBD_FREE_PTR(o);
6526
6527         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
6528 }
6529
6530 static struct lu_device *osd_device_free(const struct lu_env *env,
6531                                          struct lu_device *d)
6532 {
6533         struct osd_device *o = osd_dev(d);
6534         ENTRY;
6535
6536         /* XXX: make osd top device in order to release reference */
6537         d->ld_site->ls_top_dev = d;
6538         lu_site_purge(env, d->ld_site, -1);
6539         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
6540                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
6541                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
6542         }
6543         lu_site_fini(&o->od_site);
6544         dt_device_fini(&o->od_dt_dev);
6545         OBD_FREE_PTR(o);
6546         RETURN(NULL);
6547 }
6548
6549 static int osd_process_config(const struct lu_env *env,
6550                               struct lu_device *d, struct lustre_cfg *cfg)
6551 {
6552         struct osd_device               *o = osd_dev(d);
6553         int                             rc;
6554         ENTRY;
6555
6556         switch (cfg->lcfg_command) {
6557         case LCFG_SETUP:
6558                 rc = osd_mount(env, o, cfg);
6559                 break;
6560         case LCFG_CLEANUP:
6561                 lu_dev_del_linkage(d->ld_site, d);
6562                 rc = osd_shutdown(env, o);
6563                 break;
6564         case LCFG_PARAM:
6565                 LASSERT(&o->od_dt_dev);
6566                 rc = class_process_proc_param(PARAM_OSD, lprocfs_osd_obd_vars,
6567                                               cfg, &o->od_dt_dev);
6568                 if (rc > 0 || rc == -ENOSYS)
6569                         rc = class_process_proc_param(PARAM_OST,
6570                                                       lprocfs_osd_obd_vars,
6571                                                       cfg, &o->od_dt_dev);
6572                 break;
6573         default:
6574                 rc = -ENOSYS;
6575         }
6576
6577         RETURN(rc);
6578 }
6579
6580 static int osd_recovery_complete(const struct lu_env *env,
6581                                  struct lu_device *d)
6582 {
6583         struct osd_device       *osd = osd_dev(d);
6584         int                      rc = 0;
6585         ENTRY;
6586
6587         if (osd->od_quota_slave == NULL)
6588                 RETURN(0);
6589
6590         /* start qsd instance on recovery completion, this notifies the quota
6591          * slave code that we are about to process new requests now */
6592         rc = qsd_start(env, osd->od_quota_slave);
6593         RETURN(rc);
6594 }
6595
6596 /*
6597  * we use exports to track all osd users
6598  */
6599 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
6600                            struct obd_device *obd, struct obd_uuid *cluuid,
6601                            struct obd_connect_data *data, void *localdata)
6602 {
6603         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
6604         struct lustre_handle  conn;
6605         int                   rc;
6606         ENTRY;
6607
6608         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
6609
6610         rc = class_connect(&conn, obd, cluuid);
6611         if (rc)
6612                 RETURN(rc);
6613
6614         *exp = class_conn2export(&conn);
6615
6616         spin_lock(&osd->od_osfs_lock);
6617         osd->od_connects++;
6618         spin_unlock(&osd->od_osfs_lock);
6619
6620         RETURN(0);
6621 }
6622
6623 /*
6624  * once last export (we don't count self-export) disappeared
6625  * osd can be released
6626  */
6627 static int osd_obd_disconnect(struct obd_export *exp)
6628 {
6629         struct obd_device *obd = exp->exp_obd;
6630         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
6631         int                rc, release = 0;
6632         ENTRY;
6633
6634         /* Only disconnect the underlying layers on the final disconnect. */
6635         spin_lock(&osd->od_osfs_lock);
6636         osd->od_connects--;
6637         if (osd->od_connects == 0)
6638                 release = 1;
6639         spin_unlock(&osd->od_osfs_lock);
6640
6641         rc = class_disconnect(exp); /* bz 9811 */
6642
6643         if (rc == 0 && release)
6644                 class_manual_cleanup(obd);
6645         RETURN(rc);
6646 }
6647
6648 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
6649                        struct lu_device *dev)
6650 {
6651         struct osd_device       *osd    = osd_dev(dev);
6652         struct lr_server_data   *lsd    =
6653                         &osd->od_dt_dev.dd_lu_dev.ld_site->ls_tgt->lut_lsd;
6654         int                      result = 0;
6655         ENTRY;
6656
6657         if (osd->od_quota_slave != NULL) {
6658                 /* set up quota slave objects */
6659                 result = qsd_prepare(env, osd->od_quota_slave);
6660                 if (result != 0)
6661                         RETURN(result);
6662         }
6663
6664         if (lsd->lsd_feature_incompat & OBD_COMPAT_OST) {
6665 #if LUSTRE_VERSION_CODE < OBD_OCD_VERSION(3, 0, 52, 0)
6666                 if (lsd->lsd_feature_rocompat & OBD_ROCOMPAT_IDX_IN_IDIF) {
6667                         osd->od_index_in_idif = 1;
6668                 } else {
6669                         osd->od_index_in_idif = 0;
6670                         result = osd_register_proc_index_in_idif(osd);
6671                         if (result != 0)
6672                                 RETURN(result);
6673                 }
6674 #else
6675                 osd->od_index_in_idif = 1;
6676 #endif
6677         }
6678
6679         result = osd_fid_init(env, osd);
6680
6681         RETURN(result);
6682 }
6683
6684 static int osd_fid_alloc(const struct lu_env *env, struct obd_export *exp,
6685                          struct lu_fid *fid, struct md_op_data *op_data)
6686 {
6687         struct osd_device *osd = osd_dev(exp->exp_obd->obd_lu_dev);
6688
6689         return seq_client_alloc_fid(env, osd->od_cl_seq, fid);
6690 }
6691
6692 static const struct lu_object_operations osd_lu_obj_ops = {
6693         .loo_object_init      = osd_object_init,
6694         .loo_object_delete    = osd_object_delete,
6695         .loo_object_release   = osd_object_release,
6696         .loo_object_free      = osd_object_free,
6697         .loo_object_print     = osd_object_print,
6698         .loo_object_invariant = osd_object_invariant
6699 };
6700
6701 const struct lu_device_operations osd_lu_ops = {
6702         .ldo_object_alloc      = osd_object_alloc,
6703         .ldo_process_config    = osd_process_config,
6704         .ldo_recovery_complete = osd_recovery_complete,
6705         .ldo_prepare           = osd_prepare,
6706 };
6707
6708 static const struct lu_device_type_operations osd_device_type_ops = {
6709         .ldto_init = osd_type_init,
6710         .ldto_fini = osd_type_fini,
6711
6712         .ldto_start = osd_type_start,
6713         .ldto_stop  = osd_type_stop,
6714
6715         .ldto_device_alloc = osd_device_alloc,
6716         .ldto_device_free  = osd_device_free,
6717
6718         .ldto_device_init    = osd_device_init,
6719         .ldto_device_fini    = osd_device_fini
6720 };
6721
6722 static struct lu_device_type osd_device_type = {
6723         .ldt_tags     = LU_DEVICE_DT,
6724         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
6725         .ldt_ops      = &osd_device_type_ops,
6726         .ldt_ctx_tags = LCT_LOCAL,
6727 };
6728
6729 static int osd_health_check(const struct lu_env *env, struct obd_device *obd)
6730 {
6731         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
6732         struct super_block *sb = osd_sb(osd);
6733
6734         return (osd->od_mnt == NULL || sb->s_flags & MS_RDONLY);
6735 }
6736
6737 /*
6738  * lprocfs legacy support.
6739  */
6740 static struct obd_ops osd_obd_device_ops = {
6741         .o_owner = THIS_MODULE,
6742         .o_connect      = osd_obd_connect,
6743         .o_disconnect   = osd_obd_disconnect,
6744         .o_fid_alloc    = osd_fid_alloc,
6745         .o_health_check = osd_health_check,
6746 };
6747
6748 static int __init osd_init(void)
6749 {
6750         int rc;
6751
6752         LASSERT(BH_DXLock < sizeof(((struct buffer_head *)0)->b_state) * 8);
6753 #if !defined(CONFIG_DEBUG_MUTEXES) && !defined(CONFIG_DEBUG_SPINLOCK)
6754         /* please, try to keep osd_thread_info smaller than a page */
6755         CLASSERT(sizeof(struct osd_thread_info) <= PAGE_SIZE);
6756 #endif
6757
6758         osd_oi_mod_init();
6759
6760         rc = lu_kmem_init(ldiskfs_caches);
6761         if (rc)
6762                 return rc;
6763
6764         rc = class_register_type(&osd_obd_device_ops, NULL, true,
6765                                  lprocfs_osd_module_vars,
6766                                  LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
6767         if (rc)
6768                 lu_kmem_fini(ldiskfs_caches);
6769         return rc;
6770 }
6771
6772 static void __exit osd_exit(void)
6773 {
6774         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
6775         lu_kmem_fini(ldiskfs_caches);
6776 }
6777
6778 MODULE_AUTHOR("OpenSFS, Inc. <http://www.lustre.org/>");
6779 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
6780 MODULE_VERSION(LUSTRE_VERSION_STRING);
6781 MODULE_LICENSE("GPL");
6782
6783 module_init(osd_init);
6784 module_exit(osd_exit);