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