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