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