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