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