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