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