Whamcloud - gitweb
523cfdf31f6299f97686e772d7fc9ac051c92c2a
[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.sun.com/software/products/lustre/docs/GPLv2.pdf
19  *
20  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
21  * CA 95054 USA or visit www.sun.com if you need additional information or
22  * have any questions.
23  *
24  * GPL HEADER END
25  */
26 /*
27  * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
28  * Use is subject to license terms.
29  *
30  * Copyright (c) 2011, 2013, Intel Corporation.
31  */
32 /*
33  * This file is part of Lustre, http://www.lustre.org/
34  * Lustre is a trademark of Sun Microsystems, Inc.
35  *
36  * lustre/osd/osd_handler.c
37  *
38  * Top-level entry points into osd module
39  *
40  * Author: Nikita Danilov <nikita@clusterfs.com>
41  *         Pravin Shelar <pravin.shelar@sun.com> : Added fid in dirent
42  */
43
44 #define DEBUG_SUBSYSTEM S_MDS
45
46 #include <linux/module.h>
47
48 /* LUSTRE_VERSION_CODE */
49 #include <lustre_ver.h>
50 /* prerequisite for linux/xattr.h */
51 #include <linux/types.h>
52 /* prerequisite for linux/xattr.h */
53 #include <linux/fs.h>
54 /* XATTR_{REPLACE,CREATE} */
55 #include <linux/xattr.h>
56
57 /*
58  * struct OBD_{ALLOC,FREE}*()
59  * OBD_FAIL_CHECK
60  */
61 #include <obd_support.h>
62 /* struct ptlrpc_thread */
63 #include <lustre_net.h>
64 #include <lustre_fid.h>
65
66 #include "osd_internal.h"
67
68 /* llo_* api support */
69 #include <md_object.h>
70 #include <lustre_quota.h>
71
72 int ldiskfs_pdo = 1;
73 CFS_MODULE_PARM(ldiskfs_pdo, "i", int, 0644,
74                 "ldiskfs with parallel directory operations");
75
76 int ldiskfs_track_declares_assert;
77 CFS_MODULE_PARM(ldiskfs_track_declares_assert, "i", int, 0644,
78                 "LBUG during tracking of declares");
79
80 static const char dot[] = ".";
81 static const char dotdot[] = "..";
82 static const char remote_obj_dir[] = "REM_OBJ_DIR";
83
84 static const struct lu_object_operations      osd_lu_obj_ops;
85 static const struct dt_object_operations      osd_obj_ops;
86 static const struct dt_object_operations      osd_obj_ea_ops;
87 static const struct dt_object_operations      osd_obj_otable_it_ops;
88 static const struct dt_index_operations       osd_index_iam_ops;
89 static const struct dt_index_operations       osd_index_ea_ops;
90
91 int osd_trans_declare_op2rb[] = {
92         [OSD_OT_ATTR_SET]       = OSD_OT_ATTR_SET,
93         [OSD_OT_PUNCH]          = OSD_OT_MAX,
94         [OSD_OT_XATTR_SET]      = OSD_OT_XATTR_SET,
95         [OSD_OT_CREATE]         = OSD_OT_DESTROY,
96         [OSD_OT_DESTROY]        = OSD_OT_CREATE,
97         [OSD_OT_REF_ADD]        = OSD_OT_REF_DEL,
98         [OSD_OT_REF_DEL]        = OSD_OT_REF_ADD,
99         [OSD_OT_WRITE]          = OSD_OT_WRITE,
100         [OSD_OT_INSERT]         = OSD_OT_DELETE,
101         [OSD_OT_DELETE]         = OSD_OT_INSERT,
102         [OSD_OT_UPDATE]         = OSD_OT_MAX,
103         [OSD_OT_QUOTA]          = OSD_OT_MAX,
104 };
105
106 static int osd_has_index(const struct osd_object *obj)
107 {
108         return obj->oo_dt.do_index_ops != NULL;
109 }
110
111 static int osd_object_invariant(const struct lu_object *l)
112 {
113         return osd_invariant(osd_obj(l));
114 }
115
116 /*
117  * Concurrency: doesn't matter
118  */
119 static int osd_read_locked(const struct lu_env *env, struct osd_object *o)
120 {
121         return osd_oti_get(env)->oti_r_locks > 0;
122 }
123
124 /*
125  * Concurrency: doesn't matter
126  */
127 static int osd_write_locked(const struct lu_env *env, struct osd_object *o)
128 {
129         struct osd_thread_info *oti = osd_oti_get(env);
130         return oti->oti_w_locks > 0 && o->oo_owner == env;
131 }
132
133 /*
134  * Concurrency: doesn't access mutable data
135  */
136 static int osd_root_get(const struct lu_env *env,
137                         struct dt_device *dev, struct lu_fid *f)
138 {
139         lu_local_obj_fid(f, OSD_FS_ROOT_OID);
140         return 0;
141 }
142
143 /*
144  * OSD object methods.
145  */
146
147 /*
148  * Concurrency: no concurrent access is possible that early in object
149  * life-cycle.
150  */
151 static struct lu_object *osd_object_alloc(const struct lu_env *env,
152                                           const struct lu_object_header *hdr,
153                                           struct lu_device *d)
154 {
155         struct osd_object *mo;
156
157         OBD_ALLOC_PTR(mo);
158         if (mo != NULL) {
159                 struct lu_object *l;
160
161                 l = &mo->oo_dt.do_lu;
162                 dt_object_init(&mo->oo_dt, NULL, d);
163                 mo->oo_dt.do_ops = &osd_obj_ea_ops;
164                 l->lo_ops = &osd_lu_obj_ops;
165                 init_rwsem(&mo->oo_sem);
166                 init_rwsem(&mo->oo_ext_idx_sem);
167                 spin_lock_init(&mo->oo_guard);
168                 return l;
169         } else {
170                 return NULL;
171         }
172 }
173
174 int osd_get_lma(struct osd_thread_info *info, struct inode *inode,
175                 struct dentry *dentry, struct lustre_mdt_attrs *lma)
176 {
177         int rc;
178
179         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
180         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
181                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
182         if (rc > 0) {
183                 if ((void *)lma != (void *)info->oti_mdt_attrs_old)
184                         memcpy(lma, info->oti_mdt_attrs_old, sizeof(*lma));
185                 rc = 0;
186                 lustre_lma_swab(lma);
187                 /* Check LMA compatibility */
188                 if (lma->lma_incompat & ~LMA_INCOMPAT_SUPP) {
189                         CWARN("%.16s: unsupported incompat LMA feature(s) %#x "
190                               "for fid = "DFID", ino = %lu\n",
191                               LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
192                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
193                               PFID(&lma->lma_self_fid), inode->i_ino);
194                         rc = -EOPNOTSUPP;
195                 }
196         } else if (rc == 0) {
197                 rc = -ENODATA;
198         }
199
200         return rc;
201 }
202
203 /*
204  * retrieve object from backend ext fs.
205  **/
206 struct inode *osd_iget(struct osd_thread_info *info, struct osd_device *dev,
207                        struct osd_inode_id *id)
208 {
209         struct inode *inode = NULL;
210
211         inode = ldiskfs_iget(osd_sb(dev), id->oii_ino);
212         if (IS_ERR(inode)) {
213                 CDEBUG(D_INODE, "no inode: ino = %u, rc = %ld\n",
214                        id->oii_ino, PTR_ERR(inode));
215         } else if (id->oii_gen != OSD_OII_NOGEN &&
216                    inode->i_generation != id->oii_gen) {
217                 CDEBUG(D_INODE, "unmatched inode: ino = %u, gen0 = %u, "
218                        "gen1 = %u\n",
219                        id->oii_ino, id->oii_gen, inode->i_generation);
220                 iput(inode);
221                 inode = ERR_PTR(-ESTALE);
222         } else if (inode->i_nlink == 0) {
223                 /* due to parallel readdir and unlink,
224                 * we can have dead inode here. */
225                 CDEBUG(D_INODE, "stale inode: ino = %u\n", id->oii_ino);
226                 make_bad_inode(inode);
227                 iput(inode);
228                 inode = ERR_PTR(-ESTALE);
229         } else if (is_bad_inode(inode)) {
230                 CWARN("%.16s: bad inode: ino = %u\n",
231                 LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name, id->oii_ino);
232                 iput(inode);
233                 inode = ERR_PTR(-ENOENT);
234         } else {
235                 if (id->oii_gen == OSD_OII_NOGEN)
236                         osd_id_gen(id, inode->i_ino, inode->i_generation);
237
238                 /* Do not update file c/mtime in ldiskfs.
239                  * NB: we don't have any lock to protect this because we don't
240                  * have reference on osd_object now, but contention with
241                  * another lookup + attr_set can't happen in the tiny window
242                  * between if (...) and set S_NOCMTIME. */
243                 if (!(inode->i_flags & S_NOCMTIME))
244                         inode->i_flags |= S_NOCMTIME;
245         }
246         return inode;
247 }
248
249 static struct inode *
250 osd_iget_fid(struct osd_thread_info *info, struct osd_device *dev,
251              struct osd_inode_id *id, struct lu_fid *fid)
252 {
253         struct lustre_mdt_attrs *lma   = &info->oti_mdt_attrs;
254         struct inode            *inode;
255         int                      rc;
256
257         inode = osd_iget(info, dev, id);
258         if (IS_ERR(inode))
259                 return inode;
260
261         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
262         if (rc == 0) {
263                 *fid = lma->lma_self_fid;
264         } else if (rc == -ENODATA) {
265                 if (unlikely(inode == osd_sb(dev)->s_root->d_inode))
266                         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
267                 else
268                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
269         } else {
270                 iput(inode);
271                 inode = ERR_PTR(rc);
272         }
273         return inode;
274 }
275
276 /**
277  * \retval +v: new filter_fid, does not contain self-fid
278  * \retval 0:  filter_fid_old, contains self-fid
279  * \retval -v: other failure cases
280  */
281 int osd_get_idif(struct osd_thread_info *info, struct inode *inode,
282                  struct dentry *dentry, struct lu_fid *fid)
283 {
284         struct filter_fid_old   *ff     = &info->oti_ff;
285         struct ost_id           *ostid  = &info->oti_ostid;
286         int                      rc;
287
288         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_FID, ff, sizeof(*ff));
289         if (rc == sizeof(*ff)) {
290                 rc = 0;
291                 ostid_set_seq(ostid, le64_to_cpu(ff->ff_seq));
292                 ostid_set_id(ostid, le64_to_cpu(ff->ff_objid));
293                 /* XXX: should use real OST index in the future. LU-3569 */
294                 ostid_to_fid(fid, ostid, 0);
295         } else if (rc == sizeof(struct filter_fid)) {
296                 rc = 1;
297         } else if (rc >= 0) {
298                 rc = -EINVAL;
299         }
300
301         return rc;
302 }
303
304 static int osd_check_lma(const struct lu_env *env, struct osd_object *obj)
305 {
306         struct osd_thread_info  *info   = osd_oti_get(env);
307         struct lustre_mdt_attrs *lma    = &info->oti_mdt_attrs;
308         struct inode            *inode  = obj->oo_inode;
309         struct dentry           *dentry = &info->oti_obj_dentry;
310         struct lu_fid           *fid    = NULL;
311         int                      rc;
312         ENTRY;
313
314         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_COMPAT_INVALID_ENTRY))
315                 RETURN(0);
316
317         CLASSERT(LMA_OLD_SIZE >= sizeof(*lma));
318         rc = __osd_xattr_get(inode, dentry, XATTR_NAME_LMA,
319                              info->oti_mdt_attrs_old, LMA_OLD_SIZE);
320         if (rc == -ENODATA) {
321                 fid = &lma->lma_self_fid;
322                 rc = osd_get_idif(info, inode, dentry, fid);
323                 if (rc > 0)
324                         rc = 0;
325         }
326
327         if (unlikely(rc == -ENODATA))
328                 RETURN(0);
329
330         if (rc < 0)
331                 RETURN(rc);
332
333         if (rc > 0) {
334                 rc = 0;
335                 lustre_lma_swab(lma);
336                 if (unlikely((lma->lma_incompat & ~LMA_INCOMPAT_SUPP) ||
337                              CFS_FAIL_CHECK(OBD_FAIL_OSD_LMA_INCOMPAT))) {
338                         CWARN("%s: unsupported incompat LMA feature(s) %#x for "
339                               "fid = "DFID", ino = %lu\n",
340                               osd_obj2dev(obj)->od_svname,
341                               lma->lma_incompat & ~LMA_INCOMPAT_SUPP,
342                               PFID(lu_object_fid(&obj->oo_dt.do_lu)),
343                               inode->i_ino);
344                         rc = -EOPNOTSUPP;
345                 } else if (!(lma->lma_compat & LMAC_NOT_IN_OI)) {
346                         fid = &lma->lma_self_fid;
347                 }
348         }
349
350         if (fid != NULL &&
351             unlikely(!lu_fid_eq(lu_object_fid(&obj->oo_dt.do_lu), fid))) {
352                 CDEBUG(D_INODE, "%s: FID "DFID" != self_fid "DFID"\n",
353                        osd_obj2dev(obj)->od_svname,
354                        PFID(lu_object_fid(&obj->oo_dt.do_lu)),
355                        PFID(&lma->lma_self_fid));
356                 rc = -EREMCHG;
357         }
358
359         RETURN(rc);
360 }
361
362 static int osd_fid_lookup(const struct lu_env *env, struct osd_object *obj,
363                           const struct lu_fid *fid,
364                           const struct lu_object_conf *conf)
365 {
366         struct osd_thread_info *info;
367         struct lu_device       *ldev   = obj->oo_dt.do_lu.lo_dev;
368         struct osd_device      *dev;
369         struct osd_idmap_cache *oic;
370         struct osd_inode_id    *id;
371         struct inode           *inode;
372         struct osd_scrub       *scrub;
373         struct scrub_file      *sf;
374         int                     result;
375         int                     saved  = 0;
376         bool                    in_oi  = false;
377         bool                    triggered = false;
378         ENTRY;
379
380         LINVRNT(osd_invariant(obj));
381         LASSERT(obj->oo_inode == NULL);
382         LASSERTF(fid_is_sane(fid) || fid_is_idif(fid), DFID, PFID(fid));
383
384         dev = osd_dev(ldev);
385         scrub = &dev->od_scrub;
386         sf = &scrub->os_file;
387         info = osd_oti_get(env);
388         LASSERT(info);
389         oic = &info->oti_cache;
390
391         if (OBD_FAIL_CHECK(OBD_FAIL_OST_ENOENT))
392                 RETURN(-ENOENT);
393
394         /* Search order: 1. per-thread cache. */
395         if (lu_fid_eq(fid, &oic->oic_fid)) {
396                 id = &oic->oic_lid;
397                 goto iget;
398         }
399
400         id = &info->oti_id;
401         if (!cfs_list_empty(&scrub->os_inconsistent_items)) {
402                 /* Search order: 2. OI scrub pending list. */
403                 result = osd_oii_lookup(dev, fid, id);
404                 if (result == 0)
405                         goto iget;
406         }
407
408         /*
409          * Objects are created as locking anchors or place holders for objects
410          * yet to be created. No need to osd_oi_lookup() at here because FID
411          * shouldn't never be re-used, if it's really a duplicate FID from
412          * unexpected reason, we should be able to detect it later by calling
413          * do_create->osd_oi_insert()
414          */
415         if (conf != NULL && conf->loc_flags & LOC_F_NEW)
416                 GOTO(out, result = 0);
417
418         /* Search order: 3. OI files. */
419         result = osd_oi_lookup(info, dev, fid, id, OI_CHECK_FLD);
420         if (result == -ENOENT) {
421                 if (!fid_is_norm(fid) ||
422                     fid_is_on_ost(info, dev, fid, OI_CHECK_FLD) ||
423                     !ldiskfs_test_bit(osd_oi_fid2idx(dev,fid),
424                                       sf->sf_oi_bitmap))
425                         GOTO(out, result = 0);
426
427                 goto trigger;
428         }
429
430         if (result != 0)
431                 GOTO(out, result);
432
433         in_oi = true;
434
435 iget:
436         inode = osd_iget(info, dev, id);
437         if (IS_ERR(inode)) {
438                 result = PTR_ERR(inode);
439                 if (result == -ENOENT || result == -ESTALE) {
440                         if (!in_oi) {
441                                 fid_zero(&oic->oic_fid);
442                                 GOTO(out, result = 0);
443                         }
444
445                         /* XXX: There are three possible cases:
446                          *      1. Backup/restore caused the OI invalid.
447                          *      2. Someone unlinked the object but NOT removed
448                          *         the OI mapping, such as mount target device
449                          *         as ldiskfs, and modify something directly.
450                          *      3. Someone just removed the object between the
451                          *         former oi_lookup and the iget. It is normal.
452                          *
453                          *      It is diffcult to distinguish the 2nd from the
454                          *      1st case. Relatively speaking, the 1st case is
455                          *      common than the 2nd case, trigger OI scrub. */
456                         result = osd_oi_lookup(info, dev, fid, id, true);
457                         if (result == 0)
458                                 /* It is the case 1 or 2. */
459                                 goto trigger;
460
461                         if (result == -ENOENT)
462                                 /* It is the case 3. */
463                                 result = 0;
464                 } else if (result == -EREMCHG) {
465
466 trigger:
467                         if (unlikely(triggered))
468                                 GOTO(out, result = saved);
469
470                         triggered = true;
471                         if (thread_is_running(&scrub->os_thread)) {
472                                 result = -EINPROGRESS;
473                         } else if (!dev->od_noscrub) {
474                                 result = osd_scrub_start(dev);
475                                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC "
476                                                "for "DFID", rc = %d [1]\n",
477                                                LDISKFS_SB(osd_sb(dev))->s_es->\
478                                                s_volume_name,PFID(fid), result);
479                                 if (result == 0 || result == -EALREADY)
480                                         result = -EINPROGRESS;
481                                 else
482                                         result = -EREMCHG;
483                         }
484
485                         /* We still have chance to get the valid inode: for the
486                          * object which is referenced by remote name entry, the
487                          * object on the local MDT will be linked under the dir
488                          * of "/REMOTE_PARENT_DIR" with its FID string as name.
489                          *
490                          * We do not know whether the object for the given FID
491                          * is referenced by some remote name entry or not, and
492                          * especially for DNE II, a multiple-linked object may
493                          * have many name entries reside on many MDTs.
494                          *
495                          * To simplify the operation, OSD will not distinguish
496                          * more, just lookup "/REMOTE_PARENT_DIR". Usually, it
497                          * only happened for the RPC from other MDT during the
498                          * OI scrub, or for the client side RPC with FID only,
499                          * such as FID to path, or from old connected client. */
500                         saved = result;
501                         result = osd_lookup_in_remote_parent(info, dev,
502                                                              fid, id);
503                         if (result == 0) {
504                                 in_oi = false;
505                                 goto iget;
506                         }
507
508                         result = saved;
509                 }
510
511                 GOTO(out, result);
512         }
513
514         obj->oo_inode = inode;
515         LASSERT(obj->oo_inode->i_sb == osd_sb(dev));
516
517         result = osd_check_lma(env, obj);
518         if (result != 0) {
519                 iput(inode);
520                 obj->oo_inode = NULL;
521                 if (result == -EREMCHG)
522                         goto trigger;
523
524                 GOTO(out, result);
525         }
526
527         obj->oo_compat_dot_created = 1;
528         obj->oo_compat_dotdot_created = 1;
529
530         if (!S_ISDIR(inode->i_mode) || !ldiskfs_pdo) /* done */
531                 GOTO(out, result = 0);
532
533         LASSERT(obj->oo_hl_head == NULL);
534         obj->oo_hl_head = ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
535         if (obj->oo_hl_head == NULL) {
536                 obj->oo_inode = NULL;
537                 iput(inode);
538                 GOTO(out, result = -ENOMEM);
539         }
540         GOTO(out, result = 0);
541
542 out:
543         LINVRNT(osd_invariant(obj));
544         return result;
545 }
546
547 /*
548  * Concurrency: shouldn't matter.
549  */
550 static void osd_object_init0(struct osd_object *obj)
551 {
552         LASSERT(obj->oo_inode != NULL);
553         obj->oo_dt.do_body_ops = &osd_body_ops;
554         obj->oo_dt.do_lu.lo_header->loh_attr |=
555                 (LOHA_EXISTS | (obj->oo_inode->i_mode & S_IFMT));
556 }
557
558 /*
559  * Concurrency: no concurrent access is possible that early in object
560  * life-cycle.
561  */
562 static int osd_object_init(const struct lu_env *env, struct lu_object *l,
563                            const struct lu_object_conf *conf)
564 {
565         struct osd_object *obj = osd_obj(l);
566         int result;
567
568         LINVRNT(osd_invariant(obj));
569
570         if (fid_is_otable_it(&l->lo_header->loh_fid)) {
571                 obj->oo_dt.do_ops = &osd_obj_otable_it_ops;
572                 l->lo_header->loh_attr |= LOHA_EXISTS;
573                 return 0;
574         }
575
576         result = osd_fid_lookup(env, obj, lu_object_fid(l), conf);
577         obj->oo_dt.do_body_ops = &osd_body_ops_new;
578         if (result == 0 && obj->oo_inode != NULL)
579                 osd_object_init0(obj);
580
581         LINVRNT(osd_invariant(obj));
582         return result;
583 }
584
585 /*
586  * Concurrency: no concurrent access is possible that late in object
587  * life-cycle.
588  */
589 static void osd_object_free(const struct lu_env *env, struct lu_object *l)
590 {
591         struct osd_object *obj = osd_obj(l);
592
593         LINVRNT(osd_invariant(obj));
594
595         dt_object_fini(&obj->oo_dt);
596         if (obj->oo_hl_head != NULL)
597                 ldiskfs_htree_lock_head_free(obj->oo_hl_head);
598         OBD_FREE_PTR(obj);
599 }
600
601 /*
602  * Concurrency: no concurrent access is possible that late in object
603  * life-cycle.
604  */
605 static void osd_index_fini(struct osd_object *o)
606 {
607         struct iam_container *bag;
608
609         if (o->oo_dir != NULL) {
610                 bag = &o->oo_dir->od_container;
611                 if (o->oo_inode != NULL) {
612                         if (bag->ic_object == o->oo_inode)
613                                 iam_container_fini(bag);
614                 }
615                 OBD_FREE_PTR(o->oo_dir);
616                 o->oo_dir = NULL;
617         }
618 }
619
620 /*
621  * Concurrency: no concurrent access is possible that late in object
622  * life-cycle (for all existing callers, that is. New callers have to provide
623  * their own locking.)
624  */
625 static int osd_inode_unlinked(const struct inode *inode)
626 {
627         return inode->i_nlink == 0;
628 }
629
630 enum {
631         OSD_TXN_OI_DELETE_CREDITS    = 20,
632         OSD_TXN_INODE_DELETE_CREDITS = 20
633 };
634
635 /*
636  * Journal
637  */
638
639 #if OSD_THANDLE_STATS
640 /**
641  * Set time when the handle is allocated
642  */
643 static void osd_th_alloced(struct osd_thandle *oth)
644 {
645         oth->oth_alloced = cfs_time_current();
646 }
647
648 /**
649  * Set time when the handle started
650  */
651 static void osd_th_started(struct osd_thandle *oth)
652 {
653         oth->oth_started = cfs_time_current();
654 }
655
656 /**
657  * Helper function to convert time interval to microseconds packed in
658  * long int.
659  */
660 static long interval_to_usec(cfs_time_t start, cfs_time_t end)
661 {
662         struct timeval val;
663
664         cfs_duration_usec(cfs_time_sub(end, start), &val);
665         return val.tv_sec * 1000000 + val.tv_usec;
666 }
667
668 /**
669  * Check whether the we deal with this handle for too long.
670  */
671 static void __osd_th_check_slow(void *oth, struct osd_device *dev,
672                                 cfs_time_t alloced, cfs_time_t started,
673                                 cfs_time_t closed)
674 {
675         cfs_time_t now = cfs_time_current();
676
677         LASSERT(dev != NULL);
678
679         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_STARTING,
680                             interval_to_usec(alloced, started));
681         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_OPEN,
682                             interval_to_usec(started, closed));
683         lprocfs_counter_add(dev->od_stats, LPROC_OSD_THANDLE_CLOSING,
684                             interval_to_usec(closed, now));
685
686         if (cfs_time_before(cfs_time_add(alloced, cfs_time_seconds(30)), now)) {
687                 CWARN("transaction handle %p was open for too long: "
688                       "now "CFS_TIME_T" ,"
689                       "alloced "CFS_TIME_T" ,"
690                       "started "CFS_TIME_T" ,"
691                       "closed "CFS_TIME_T"\n",
692                       oth, now, alloced, started, closed);
693                 libcfs_debug_dumpstack(NULL);
694         }
695 }
696
697 #define OSD_CHECK_SLOW_TH(oth, dev, expr)                               \
698 {                                                                       \
699         cfs_time_t __closed = cfs_time_current();                       \
700         cfs_time_t __alloced = oth->oth_alloced;                        \
701         cfs_time_t __started = oth->oth_started;                        \
702                                                                         \
703         expr;                                                           \
704         __osd_th_check_slow(oth, dev, __alloced, __started, __closed);  \
705 }
706
707 #else /* OSD_THANDLE_STATS */
708
709 #define osd_th_alloced(h)                  do {} while(0)
710 #define osd_th_started(h)                  do {} while(0)
711 #define OSD_CHECK_SLOW_TH(oth, dev, expr)  expr
712
713 #endif /* OSD_THANDLE_STATS */
714
715 /*
716  * Concurrency: doesn't access mutable data.
717  */
718 static int osd_param_is_not_sane(const struct osd_device *dev,
719                                  const struct thandle *th)
720 {
721         struct osd_thandle *oh = container_of(th, typeof(*oh), ot_super);
722
723         return oh->ot_credits > osd_journal(dev)->j_max_transaction_buffers;
724 }
725
726 /*
727  * Concurrency: shouldn't matter.
728  */
729 static void osd_trans_commit_cb(struct super_block *sb,
730                                 struct ldiskfs_journal_cb_entry *jcb, int error)
731 {
732         struct osd_thandle *oh = container_of0(jcb, struct osd_thandle, ot_jcb);
733         struct thandle     *th  = &oh->ot_super;
734         struct lu_device   *lud = &th->th_dev->dd_lu_dev;
735         struct dt_txn_commit_cb *dcb, *tmp;
736
737         LASSERT(oh->ot_handle == NULL);
738
739         if (error)
740                 CERROR("transaction @0x%p commit error: %d\n", th, error);
741
742         dt_txn_hook_commit(th);
743
744         /* call per-transaction callbacks if any */
745         cfs_list_for_each_entry_safe(dcb, tmp, &oh->ot_dcb_list, dcb_linkage) {
746                 LASSERTF(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC,
747                          "commit callback entry: magic=%x name='%s'\n",
748                          dcb->dcb_magic, dcb->dcb_name);
749                 cfs_list_del_init(&dcb->dcb_linkage);
750                 dcb->dcb_func(NULL, th, dcb, error);
751         }
752
753         lu_ref_del_at(&lud->ld_reference, &oh->ot_dev_link, "osd-tx", th);
754         lu_device_put(lud);
755         th->th_dev = NULL;
756
757         lu_context_exit(&th->th_ctx);
758         lu_context_fini(&th->th_ctx);
759         OBD_FREE_PTR(oh);
760 }
761
762 static struct thandle *osd_trans_create(const struct lu_env *env,
763                                         struct dt_device *d)
764 {
765         struct osd_thread_info *oti = osd_oti_get(env);
766         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
767         struct osd_thandle     *oh;
768         struct thandle         *th;
769         ENTRY;
770
771         /* on pending IO in this thread should left from prev. request */
772         LASSERT(cfs_atomic_read(&iobuf->dr_numreqs) == 0);
773
774         th = ERR_PTR(-ENOMEM);
775         OBD_ALLOC_GFP(oh, sizeof *oh, __GFP_IO);
776         if (oh != NULL) {
777                 oh->ot_quota_trans = &oti->oti_quota_trans;
778                 memset(oh->ot_quota_trans, 0, sizeof(*oh->ot_quota_trans));
779                 th = &oh->ot_super;
780                 th->th_dev = d;
781                 th->th_result = 0;
782                 th->th_tags = LCT_TX_HANDLE;
783                 oh->ot_credits = 0;
784                 oti->oti_dev = osd_dt_dev(d);
785                 CFS_INIT_LIST_HEAD(&oh->ot_dcb_list);
786                 osd_th_alloced(oh);
787
788                 memset(oti->oti_declare_ops, 0,
789                                         sizeof(oti->oti_declare_ops));
790                 memset(oti->oti_declare_ops_rb, 0,
791                                         sizeof(oti->oti_declare_ops_rb));
792                 memset(oti->oti_declare_ops_cred, 0,
793                                         sizeof(oti->oti_declare_ops_cred));
794                 oti->oti_rollback = false;
795         }
796         RETURN(th);
797 }
798
799 /*
800  * Concurrency: shouldn't matter.
801  */
802 int osd_trans_start(const struct lu_env *env, struct dt_device *d,
803                     struct thandle *th)
804 {
805         struct osd_thread_info *oti = osd_oti_get(env);
806         struct osd_device  *dev = osd_dt_dev(d);
807         handle_t           *jh;
808         struct osd_thandle *oh;
809         int rc;
810
811         ENTRY;
812
813         LASSERT(current->journal_info == NULL);
814
815         oh = container_of0(th, struct osd_thandle, ot_super);
816         LASSERT(oh != NULL);
817         LASSERT(oh->ot_handle == NULL);
818
819         rc = dt_txn_hook_start(env, d, th);
820         if (rc != 0)
821                 GOTO(out, rc);
822
823         if (unlikely(osd_param_is_not_sane(dev, th))) {
824                 static unsigned long last_printed;
825                 static int last_credits;
826
827                 CWARN("%.16s: too many transaction credits (%d > %d)\n",
828                       LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
829                       oh->ot_credits,
830                       osd_journal(dev)->j_max_transaction_buffers);
831                 CWARN("  create: %u/%u, delete: %u/%u, destroy: %u/%u\n",
832                       oti->oti_declare_ops[OSD_OT_CREATE],
833                       oti->oti_declare_ops_cred[OSD_OT_CREATE],
834                       oti->oti_declare_ops[OSD_OT_DELETE],
835                       oti->oti_declare_ops_cred[OSD_OT_DELETE],
836                       oti->oti_declare_ops[OSD_OT_DESTROY],
837                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
838                 CWARN("  attr_set: %u/%u, xattr_set: %u/%u\n",
839                       oti->oti_declare_ops[OSD_OT_ATTR_SET],
840                       oti->oti_declare_ops_cred[OSD_OT_ATTR_SET],
841                       oti->oti_declare_ops[OSD_OT_XATTR_SET],
842                       oti->oti_declare_ops_cred[OSD_OT_XATTR_SET]);
843                 CWARN("  write: %u/%u, punch: %u/%u, quota %u/%u\n",
844                       oti->oti_declare_ops[OSD_OT_WRITE],
845                       oti->oti_declare_ops_cred[OSD_OT_WRITE],
846                       oti->oti_declare_ops[OSD_OT_PUNCH],
847                       oti->oti_declare_ops_cred[OSD_OT_PUNCH],
848                       oti->oti_declare_ops[OSD_OT_QUOTA],
849                       oti->oti_declare_ops_cred[OSD_OT_QUOTA]);
850                 CWARN("  insert: %u/%u, delete: %u/%u\n",
851                       oti->oti_declare_ops[OSD_OT_INSERT],
852                       oti->oti_declare_ops_cred[OSD_OT_INSERT],
853                       oti->oti_declare_ops[OSD_OT_DESTROY],
854                       oti->oti_declare_ops_cred[OSD_OT_DESTROY]);
855                 CWARN("  ref_add: %u/%u, ref_del: %u/%u\n",
856                       oti->oti_declare_ops[OSD_OT_REF_ADD],
857                       oti->oti_declare_ops_cred[OSD_OT_REF_ADD],
858                       oti->oti_declare_ops[OSD_OT_REF_DEL],
859                       oti->oti_declare_ops_cred[OSD_OT_REF_DEL]);
860
861                 if (last_credits != oh->ot_credits &&
862                     time_after(jiffies, last_printed + 60 * HZ)) {
863                         libcfs_debug_dumpstack(NULL);
864                         last_credits = oh->ot_credits;
865                         last_printed = jiffies;
866                 }
867                 /* XXX Limit the credits to 'max_transaction_buffers', and
868                  *     let the underlying filesystem to catch the error if
869                  *     we really need so many credits.
870                  *
871                  *     This should be removed when we can calculate the
872                  *     credits precisely. */
873                 oh->ot_credits = osd_journal(dev)->j_max_transaction_buffers;
874         }
875
876         /*
877          * XXX temporary stuff. Some abstraction layer should
878          * be used.
879          */
880         jh = ldiskfs_journal_start_sb(osd_sb(dev), oh->ot_credits);
881         osd_th_started(oh);
882         if (!IS_ERR(jh)) {
883                 oh->ot_handle = jh;
884                 LASSERT(oti->oti_txns == 0);
885                 lu_context_init(&th->th_ctx, th->th_tags);
886                 lu_context_enter(&th->th_ctx);
887
888                 lu_device_get(&d->dd_lu_dev);
889                 lu_ref_add_at(&d->dd_lu_dev.ld_reference, &oh->ot_dev_link,
890                               "osd-tx", th);
891                 oti->oti_txns++;
892                 rc = 0;
893         } else {
894                 rc = PTR_ERR(jh);
895         }
896 out:
897         RETURN(rc);
898 }
899
900 /*
901  * Concurrency: shouldn't matter.
902  */
903 static int osd_trans_stop(const struct lu_env *env, struct thandle *th)
904 {
905         int                     rc = 0;
906         struct osd_thandle     *oh;
907         struct osd_thread_info *oti = osd_oti_get(env);
908         struct osd_iobuf       *iobuf = &oti->oti_iobuf;
909         struct qsd_instance    *qsd = oti->oti_dev->od_quota_slave;
910         ENTRY;
911
912         oh = container_of0(th, struct osd_thandle, ot_super);
913
914         if (qsd != NULL)
915                 /* inform the quota slave device that the transaction is
916                  * stopping */
917                 qsd_op_end(env, qsd, oh->ot_quota_trans);
918         oh->ot_quota_trans = NULL;
919
920         if (oh->ot_handle != NULL) {
921                 handle_t *hdl = oh->ot_handle;
922
923                 /*
924                  * add commit callback
925                  * notice we don't do this in osd_trans_start()
926                  * as underlying transaction can change during truncate
927                  */
928                 ldiskfs_journal_callback_add(hdl, osd_trans_commit_cb,
929                                          &oh->ot_jcb);
930
931                 LASSERT(oti->oti_txns == 1);
932                 oti->oti_txns--;
933                 rc = dt_txn_hook_stop(env, th);
934                 if (rc != 0)
935                         CERROR("Failure in transaction hook: %d\n", rc);
936
937                 /* hook functions might modify th_sync */
938                 hdl->h_sync = th->th_sync;
939
940                 oh->ot_handle = NULL;
941                 OSD_CHECK_SLOW_TH(oh, oti->oti_dev,
942                                   rc = ldiskfs_journal_stop(hdl));
943                 if (rc != 0)
944                         CERROR("Failure to stop transaction: %d\n", rc);
945         } else {
946                 OBD_FREE_PTR(oh);
947         }
948
949         /* as we want IO to journal and data IO be concurrent, we don't block
950          * awaiting data IO completion in osd_do_bio(), instead we wait here
951          * once transaction is submitted to the journal. all reqular requests
952          * don't do direct IO (except read/write), thus this wait_event becomes
953          * no-op for them.
954          *
955          * IMPORTANT: we have to wait till any IO submited by the thread is
956          * completed otherwise iobuf may be corrupted by different request
957          */
958         cfs_wait_event(iobuf->dr_wait,
959                        cfs_atomic_read(&iobuf->dr_numreqs) == 0);
960         if (!rc)
961                 rc = iobuf->dr_error;
962
963         RETURN(rc);
964 }
965
966 static int osd_trans_cb_add(struct thandle *th, struct dt_txn_commit_cb *dcb)
967 {
968         struct osd_thandle *oh = container_of0(th, struct osd_thandle,
969                                                ot_super);
970
971         LASSERT(dcb->dcb_magic == TRANS_COMMIT_CB_MAGIC);
972         LASSERT(&dcb->dcb_func != NULL);
973         cfs_list_add(&dcb->dcb_linkage, &oh->ot_dcb_list);
974
975         return 0;
976 }
977
978 /*
979  * Called just before object is freed. Releases all resources except for
980  * object itself (that is released by osd_object_free()).
981  *
982  * Concurrency: no concurrent access is possible that late in object
983  * life-cycle.
984  */
985 static void osd_object_delete(const struct lu_env *env, struct lu_object *l)
986 {
987         struct osd_object *obj   = osd_obj(l);
988         struct inode      *inode = obj->oo_inode;
989
990         LINVRNT(osd_invariant(obj));
991
992         /*
993          * If object is unlinked remove fid->ino mapping from object index.
994          */
995
996         osd_index_fini(obj);
997         if (inode != NULL) {
998                 struct qsd_instance     *qsd = osd_obj2dev(obj)->od_quota_slave;
999                 qid_t                    uid = inode->i_uid;
1000                 qid_t                    gid = inode->i_gid;
1001
1002                 iput(inode);
1003                 obj->oo_inode = NULL;
1004
1005                 if (qsd != NULL) {
1006                         struct osd_thread_info  *info = osd_oti_get(env);
1007                         struct lquota_id_info   *qi = &info->oti_qi;
1008
1009                         /* Release granted quota to master if necessary */
1010                         qi->lqi_id.qid_uid = uid;
1011                         qsd_op_adjust(env, qsd, &qi->lqi_id, USRQUOTA);
1012
1013                         qi->lqi_id.qid_uid = gid;
1014                         qsd_op_adjust(env, qsd, &qi->lqi_id, GRPQUOTA);
1015                 }
1016         }
1017 }
1018
1019 /*
1020  * Concurrency: ->loo_object_release() is called under site spin-lock.
1021  */
1022 static void osd_object_release(const struct lu_env *env,
1023                                struct lu_object *l)
1024 {
1025 }
1026
1027 /*
1028  * Concurrency: shouldn't matter.
1029  */
1030 static int osd_object_print(const struct lu_env *env, void *cookie,
1031                             lu_printer_t p, const struct lu_object *l)
1032 {
1033         struct osd_object *o = osd_obj(l);
1034         struct iam_descr  *d;
1035
1036         if (o->oo_dir != NULL)
1037                 d = o->oo_dir->od_container.ic_descr;
1038         else
1039                 d = NULL;
1040         return (*p)(env, cookie,
1041                     LUSTRE_OSD_LDISKFS_NAME"-object@%p(i:%p:%lu/%u)[%s]",
1042                     o, o->oo_inode,
1043                     o->oo_inode ? o->oo_inode->i_ino : 0UL,
1044                     o->oo_inode ? o->oo_inode->i_generation : 0,
1045                     d ? d->id_ops->id_name : "plain");
1046 }
1047
1048 /*
1049  * Concurrency: shouldn't matter.
1050  */
1051 int osd_statfs(const struct lu_env *env, struct dt_device *d,
1052                struct obd_statfs *sfs)
1053 {
1054         struct osd_device  *osd = osd_dt_dev(d);
1055         struct super_block *sb = osd_sb(osd);
1056         struct kstatfs     *ksfs;
1057         int result = 0;
1058
1059         if (unlikely(osd->od_mnt == NULL))
1060                 return -EINPROGRESS;
1061
1062         /* osd_lproc.c call this without env, allocate ksfs for that case */
1063         if (unlikely(env == NULL)) {
1064                 OBD_ALLOC_PTR(ksfs);
1065                 if (ksfs == NULL)
1066                         return -ENOMEM;
1067         } else {
1068                 ksfs = &osd_oti_get(env)->oti_ksfs;
1069         }
1070
1071         spin_lock(&osd->od_osfs_lock);
1072         /* cache 1 second */
1073         if (cfs_time_before_64(osd->od_osfs_age, cfs_time_shift_64(-1))) {
1074                 result = sb->s_op->statfs(sb->s_root, ksfs);
1075                 if (likely(result == 0)) { /* N.B. statfs can't really fail */
1076                         osd->od_osfs_age = cfs_time_current_64();
1077                         statfs_pack(&osd->od_statfs, ksfs);
1078                         if (sb->s_flags & MS_RDONLY)
1079                                 sfs->os_state = OS_STATE_READONLY;
1080                 }
1081         }
1082
1083         if (likely(result == 0))
1084                 *sfs = osd->od_statfs;
1085         spin_unlock(&osd->od_osfs_lock);
1086
1087         if (unlikely(env == NULL))
1088                 OBD_FREE_PTR(ksfs);
1089
1090         return result;
1091 }
1092
1093 /**
1094  * Estimate space needed for file creations. We assume the largest filename
1095  * which is 2^64 - 1, hence a filename of 20 chars.
1096  * This is 28 bytes per object which is 28MB for 1M objects ... no so bad.
1097  */
1098 #ifdef __LDISKFS_DIR_REC_LEN
1099 #define PER_OBJ_USAGE __LDISKFS_DIR_REC_LEN(20)
1100 #else
1101 #define PER_OBJ_USAGE LDISKFS_DIR_REC_LEN(20)
1102 #endif
1103
1104 /*
1105  * Concurrency: doesn't access mutable data.
1106  */
1107 static void osd_conf_get(const struct lu_env *env,
1108                          const struct dt_device *dev,
1109                          struct dt_device_param *param)
1110 {
1111         struct super_block *sb = osd_sb(osd_dt_dev(dev));
1112
1113         /*
1114          * XXX should be taken from not-yet-existing fs abstraction layer.
1115          */
1116         param->ddp_mnt = osd_dt_dev(dev)->od_mnt;
1117         param->ddp_max_name_len = LDISKFS_NAME_LEN;
1118         param->ddp_max_nlink    = LDISKFS_LINK_MAX;
1119         param->ddp_block_shift  = sb->s_blocksize_bits;
1120         param->ddp_mount_type     = LDD_MT_LDISKFS;
1121         param->ddp_maxbytes       = sb->s_maxbytes;
1122         /* Overhead estimate should be fairly accurate, so we really take a tiny
1123          * error margin which also avoids fragmenting the filesystem too much */
1124         param->ddp_grant_reserved = 2; /* end up to be 1.9% after conversion */
1125         /* inode are statically allocated, so per-inode space consumption
1126          * is the space consumed by the directory entry */
1127         param->ddp_inodespace     = PER_OBJ_USAGE;
1128         /* per-fragment overhead to be used by the client code */
1129         param->ddp_grant_frag     = 6 * LDISKFS_BLOCK_SIZE(sb);
1130         param->ddp_mntopts      = 0;
1131         if (test_opt(sb, XATTR_USER))
1132                 param->ddp_mntopts |= MNTOPT_USERXATTR;
1133         if (test_opt(sb, POSIX_ACL))
1134                 param->ddp_mntopts |= MNTOPT_ACL;
1135
1136 #if defined(LDISKFS_FEATURE_INCOMPAT_EA_INODE)
1137         if (LDISKFS_HAS_INCOMPAT_FEATURE(sb, LDISKFS_FEATURE_INCOMPAT_EA_INODE))
1138                 param->ddp_max_ea_size = LDISKFS_XATTR_MAX_LARGE_EA_SIZE;
1139         else
1140 #endif
1141                 param->ddp_max_ea_size = sb->s_blocksize;
1142
1143 }
1144
1145 /*
1146  * Concurrency: shouldn't matter.
1147  */
1148 static int osd_sync(const struct lu_env *env, struct dt_device *d)
1149 {
1150         CDEBUG(D_HA, "syncing OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1151         return ldiskfs_force_commit(osd_sb(osd_dt_dev(d)));
1152 }
1153
1154 /**
1155  * Start commit for OSD device.
1156  *
1157  * An implementation of dt_commit_async method for OSD device.
1158  * Asychronously starts underlayng fs sync and thereby a transaction
1159  * commit.
1160  *
1161  * \param env environment
1162  * \param d dt device
1163  *
1164  * \see dt_device_operations
1165  */
1166 static int osd_commit_async(const struct lu_env *env,
1167                             struct dt_device *d)
1168 {
1169         struct super_block *s = osd_sb(osd_dt_dev(d));
1170         ENTRY;
1171
1172         CDEBUG(D_HA, "async commit OSD %s\n", LUSTRE_OSD_LDISKFS_NAME);
1173         RETURN(s->s_op->sync_fs(s, 0));
1174 }
1175
1176 /*
1177  * Concurrency: shouldn't matter.
1178  */
1179
1180 static int osd_ro(const struct lu_env *env, struct dt_device *d)
1181 {
1182         struct super_block *sb = osd_sb(osd_dt_dev(d));
1183         struct block_device *dev = sb->s_bdev;
1184 #ifdef HAVE_DEV_SET_RDONLY
1185         struct block_device *jdev = LDISKFS_SB(sb)->journal_bdev;
1186         int rc = 0;
1187 #else
1188         int rc = -EOPNOTSUPP;
1189 #endif
1190         ENTRY;
1191
1192 #ifdef HAVE_DEV_SET_RDONLY
1193         CERROR("*** setting %s read-only ***\n", osd_dt_dev(d)->od_svname);
1194
1195         if (jdev && (jdev != dev)) {
1196                 CDEBUG(D_IOCTL | D_HA, "set journal dev %lx rdonly\n",
1197                        (long)jdev);
1198                 dev_set_rdonly(jdev);
1199         }
1200         CDEBUG(D_IOCTL | D_HA, "set dev %lx rdonly\n", (long)dev);
1201         dev_set_rdonly(dev);
1202 #else
1203         CERROR("%s: %lx CANNOT BE SET READONLY: rc = %d\n",
1204                osd_dt_dev(d)->od_svname, (long)dev, rc);
1205 #endif
1206         RETURN(rc);
1207 }
1208
1209 /*
1210  * Concurrency: serialization provided by callers.
1211  */
1212 static int osd_init_capa_ctxt(const struct lu_env *env, struct dt_device *d,
1213                               int mode, unsigned long timeout, __u32 alg,
1214                               struct lustre_capa_key *keys)
1215 {
1216         struct osd_device *dev = osd_dt_dev(d);
1217         ENTRY;
1218
1219         dev->od_fl_capa = mode;
1220         dev->od_capa_timeout = timeout;
1221         dev->od_capa_alg = alg;
1222         dev->od_capa_keys = keys;
1223         RETURN(0);
1224 }
1225
1226 /**
1227  * Note: we do not count into QUOTA here.
1228  * If we mount with --data_journal we may need more.
1229  */
1230 const int osd_dto_credits_noquota[DTO_NR] = {
1231         /**
1232          * Insert/Delete.
1233          * INDEX_EXTRA_TRANS_BLOCKS(8) +
1234          * SINGLEDATA_TRANS_BLOCKS(8)
1235          * XXX Note: maybe iam need more, since iam have more level than
1236          *           EXT3 htree.
1237          */
1238         [DTO_INDEX_INSERT]  = 16,
1239         [DTO_INDEX_DELETE]  = 16,
1240         /**
1241          * Used for OI scrub
1242          */
1243         [DTO_INDEX_UPDATE]  = 16,
1244         /**
1245          * Create a object. The same as create object in EXT3.
1246          * DATA_TRANS_BLOCKS(14) +
1247          * INDEX_EXTRA_BLOCKS(8) +
1248          * 3(inode bits, groups, GDT)
1249          */
1250         [DTO_OBJECT_CREATE] = 25,
1251         /**
1252          * XXX: real credits to be fixed
1253          */
1254         [DTO_OBJECT_DELETE] = 25,
1255         /**
1256          * Attr set credits (inode)
1257          */
1258         [DTO_ATTR_SET_BASE] = 1,
1259         /**
1260          * Xattr set. The same as xattr of EXT3.
1261          * DATA_TRANS_BLOCKS(14)
1262          * XXX Note: in original MDS implmentation INDEX_EXTRA_TRANS_BLOCKS
1263          * are also counted in. Do not know why?
1264          */
1265         [DTO_XATTR_SET]     = 14,
1266         [DTO_LOG_REC]       = 14,
1267         /**
1268          * credits for inode change during write.
1269          */
1270         [DTO_WRITE_BASE]    = 3,
1271         /**
1272          * credits for single block write.
1273          */
1274         [DTO_WRITE_BLOCK]   = 14,
1275         /**
1276          * Attr set credits for chown.
1277          * This is extra credits for setattr, and it is null without quota
1278          */
1279         [DTO_ATTR_SET_CHOWN]= 0
1280 };
1281
1282 static const struct dt_device_operations osd_dt_ops = {
1283         .dt_root_get       = osd_root_get,
1284         .dt_statfs         = osd_statfs,
1285         .dt_trans_create   = osd_trans_create,
1286         .dt_trans_start    = osd_trans_start,
1287         .dt_trans_stop     = osd_trans_stop,
1288         .dt_trans_cb_add   = osd_trans_cb_add,
1289         .dt_conf_get       = osd_conf_get,
1290         .dt_sync           = osd_sync,
1291         .dt_ro             = osd_ro,
1292         .dt_commit_async   = osd_commit_async,
1293         .dt_init_capa_ctxt = osd_init_capa_ctxt,
1294 };
1295
1296 static void osd_object_read_lock(const struct lu_env *env,
1297                                  struct dt_object *dt, unsigned role)
1298 {
1299         struct osd_object *obj = osd_dt_obj(dt);
1300         struct osd_thread_info *oti = osd_oti_get(env);
1301
1302         LINVRNT(osd_invariant(obj));
1303
1304         LASSERT(obj->oo_owner != env);
1305         down_read_nested(&obj->oo_sem, role);
1306
1307         LASSERT(obj->oo_owner == NULL);
1308         oti->oti_r_locks++;
1309 }
1310
1311 static void osd_object_write_lock(const struct lu_env *env,
1312                                   struct dt_object *dt, unsigned role)
1313 {
1314         struct osd_object *obj = osd_dt_obj(dt);
1315         struct osd_thread_info *oti = osd_oti_get(env);
1316
1317         LINVRNT(osd_invariant(obj));
1318
1319         LASSERT(obj->oo_owner != env);
1320         down_write_nested(&obj->oo_sem, role);
1321
1322         LASSERT(obj->oo_owner == NULL);
1323         obj->oo_owner = env;
1324         oti->oti_w_locks++;
1325 }
1326
1327 static void osd_object_read_unlock(const struct lu_env *env,
1328                                    struct dt_object *dt)
1329 {
1330         struct osd_object *obj = osd_dt_obj(dt);
1331         struct osd_thread_info *oti = osd_oti_get(env);
1332
1333         LINVRNT(osd_invariant(obj));
1334
1335         LASSERT(oti->oti_r_locks > 0);
1336         oti->oti_r_locks--;
1337         up_read(&obj->oo_sem);
1338 }
1339
1340 static void osd_object_write_unlock(const struct lu_env *env,
1341                                     struct dt_object *dt)
1342 {
1343         struct osd_object *obj = osd_dt_obj(dt);
1344         struct osd_thread_info *oti = osd_oti_get(env);
1345
1346         LINVRNT(osd_invariant(obj));
1347
1348         LASSERT(obj->oo_owner == env);
1349         LASSERT(oti->oti_w_locks > 0);
1350         oti->oti_w_locks--;
1351         obj->oo_owner = NULL;
1352         up_write(&obj->oo_sem);
1353 }
1354
1355 static int osd_object_write_locked(const struct lu_env *env,
1356                                    struct dt_object *dt)
1357 {
1358         struct osd_object *obj = osd_dt_obj(dt);
1359
1360         LINVRNT(osd_invariant(obj));
1361
1362         return obj->oo_owner == env;
1363 }
1364
1365 static int capa_is_sane(const struct lu_env *env,
1366                         struct osd_device *dev,
1367                         struct lustre_capa *capa,
1368                         struct lustre_capa_key *keys)
1369 {
1370         struct osd_thread_info *oti = osd_oti_get(env);
1371         struct lustre_capa *tcapa = &oti->oti_capa;
1372         struct obd_capa *oc;
1373         int i, rc = 0;
1374         ENTRY;
1375
1376         oc = capa_lookup(dev->od_capa_hash, capa, 0);
1377         if (oc) {
1378                 if (capa_is_expired(oc)) {
1379                         DEBUG_CAPA(D_ERROR, capa, "expired");
1380                         rc = -ESTALE;
1381                 }
1382                 capa_put(oc);
1383                 RETURN(rc);
1384         }
1385
1386         if (capa_is_expired_sec(capa)) {
1387                 DEBUG_CAPA(D_ERROR, capa, "expired");
1388                 RETURN(-ESTALE);
1389         }
1390
1391         spin_lock(&capa_lock);
1392         for (i = 0; i < 2; i++) {
1393                 if (keys[i].lk_keyid == capa->lc_keyid) {
1394                         oti->oti_capa_key = keys[i];
1395                         break;
1396                 }
1397         }
1398         spin_unlock(&capa_lock);
1399
1400         if (i == 2) {
1401                 DEBUG_CAPA(D_ERROR, capa, "no matched capa key");
1402                 RETURN(-ESTALE);
1403         }
1404
1405         rc = capa_hmac(tcapa->lc_hmac, capa, oti->oti_capa_key.lk_key);
1406         if (rc)
1407                 RETURN(rc);
1408
1409         if (memcmp(tcapa->lc_hmac, capa->lc_hmac, sizeof(capa->lc_hmac))) {
1410                 DEBUG_CAPA(D_ERROR, capa, "HMAC mismatch");
1411                 RETURN(-EACCES);
1412         }
1413
1414         oc = capa_add(dev->od_capa_hash, capa);
1415         capa_put(oc);
1416
1417         RETURN(0);
1418 }
1419
1420 int osd_object_auth(const struct lu_env *env, struct dt_object *dt,
1421                     struct lustre_capa *capa, __u64 opc)
1422 {
1423         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
1424         struct osd_device *dev = osd_dev(dt->do_lu.lo_dev);
1425         struct md_capainfo *ci;
1426         int rc;
1427
1428         if (!dev->od_fl_capa)
1429                 return 0;
1430
1431         if (capa == BYPASS_CAPA)
1432                 return 0;
1433
1434         ci = md_capainfo(env);
1435         if (unlikely(!ci))
1436                 return 0;
1437
1438         if (ci->mc_auth == LC_ID_NONE)
1439                 return 0;
1440
1441         if (!capa) {
1442                 CERROR("no capability is provided for fid "DFID"\n", PFID(fid));
1443                 return -EACCES;
1444         }
1445
1446         if (!lu_fid_eq(fid, &capa->lc_fid)) {
1447                 DEBUG_CAPA(D_ERROR, capa, "fid "DFID" mismatch with",
1448                            PFID(fid));
1449                 return -EACCES;
1450         }
1451
1452         if (!capa_opc_supported(capa, opc)) {
1453                 DEBUG_CAPA(D_ERROR, capa, "opc "LPX64" not supported by", opc);
1454                 return -EACCES;
1455         }
1456
1457         if ((rc = capa_is_sane(env, dev, capa, dev->od_capa_keys))) {
1458                 DEBUG_CAPA(D_ERROR, capa, "insane (rc %d)", rc);
1459                 return -EACCES;
1460         }
1461
1462         return 0;
1463 }
1464
1465 static struct timespec *osd_inode_time(const struct lu_env *env,
1466                                        struct inode *inode, __u64 seconds)
1467 {
1468         struct osd_thread_info  *oti = osd_oti_get(env);
1469         struct timespec         *t   = &oti->oti_time;
1470
1471         t->tv_sec = seconds;
1472         t->tv_nsec = 0;
1473         *t = timespec_trunc(*t, inode->i_sb->s_time_gran);
1474         return t;
1475 }
1476
1477
1478 static void osd_inode_getattr(const struct lu_env *env,
1479                               struct inode *inode, struct lu_attr *attr)
1480 {
1481         attr->la_valid      |= LA_ATIME | LA_MTIME | LA_CTIME | LA_MODE |
1482                                LA_SIZE | LA_BLOCKS | LA_UID | LA_GID |
1483                                LA_FLAGS | LA_NLINK | LA_RDEV | LA_BLKSIZE |
1484                                LA_TYPE;
1485
1486         attr->la_atime      = LTIME_S(inode->i_atime);
1487         attr->la_mtime      = LTIME_S(inode->i_mtime);
1488         attr->la_ctime      = LTIME_S(inode->i_ctime);
1489         attr->la_mode       = inode->i_mode;
1490         attr->la_size       = i_size_read(inode);
1491         attr->la_blocks     = inode->i_blocks;
1492         attr->la_uid        = inode->i_uid;
1493         attr->la_gid        = inode->i_gid;
1494         attr->la_flags      = LDISKFS_I(inode)->i_flags;
1495         attr->la_nlink      = inode->i_nlink;
1496         attr->la_rdev       = inode->i_rdev;
1497         attr->la_blksize    = 1 << inode->i_blkbits;
1498         attr->la_blkbits    = inode->i_blkbits;
1499 }
1500
1501 static int osd_attr_get(const struct lu_env *env,
1502                         struct dt_object *dt,
1503                         struct lu_attr *attr,
1504                         struct lustre_capa *capa)
1505 {
1506         struct osd_object *obj = osd_dt_obj(dt);
1507
1508         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1509         LINVRNT(osd_invariant(obj));
1510
1511         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
1512                 return -EACCES;
1513
1514         spin_lock(&obj->oo_guard);
1515         osd_inode_getattr(env, obj->oo_inode, attr);
1516         spin_unlock(&obj->oo_guard);
1517         return 0;
1518 }
1519
1520 static int osd_declare_attr_set(const struct lu_env *env,
1521                                 struct dt_object *dt,
1522                                 const struct lu_attr *attr,
1523                                 struct thandle *handle)
1524 {
1525         struct osd_thandle     *oh;
1526         struct osd_object      *obj;
1527         struct osd_thread_info *info = osd_oti_get(env);
1528         struct lquota_id_info  *qi = &info->oti_qi;
1529         long long               bspace;
1530         int                     rc = 0;
1531         bool                    allocated;
1532         ENTRY;
1533
1534         LASSERT(dt != NULL);
1535         LASSERT(handle != NULL);
1536
1537         obj = osd_dt_obj(dt);
1538         LASSERT(osd_invariant(obj));
1539
1540         oh = container_of0(handle, struct osd_thandle, ot_super);
1541         LASSERT(oh->ot_handle == NULL);
1542
1543         osd_trans_declare_op(env, oh, OSD_OT_ATTR_SET,
1544                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
1545
1546         if (attr == NULL || obj->oo_inode == NULL)
1547                 RETURN(rc);
1548
1549         bspace   = obj->oo_inode->i_blocks;
1550         bspace <<= obj->oo_inode->i_sb->s_blocksize_bits;
1551         bspace   = toqb(bspace);
1552
1553         /* Changing ownership is always preformed by super user, it should not
1554          * fail with EDQUOT.
1555          *
1556          * We still need to call the osd_declare_qid() to calculate the journal
1557          * credits for updating quota accounting files and to trigger quota
1558          * space adjustment once the operation is completed.*/
1559         if ((attr->la_valid & LA_UID) != 0 &&
1560              attr->la_uid != obj->oo_inode->i_uid) {
1561                 qi->lqi_type = USRQUOTA;
1562
1563                 /* inode accounting */
1564                 qi->lqi_is_blk = false;
1565
1566                 /* one more inode for the new owner ... */
1567                 qi->lqi_id.qid_uid = attr->la_uid;
1568                 qi->lqi_space      = 1;
1569                 allocated = (attr->la_uid == 0) ? true : false;
1570                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1571                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1572                         rc = 0;
1573                 if (rc)
1574                         RETURN(rc);
1575
1576                 /* and one less inode for the current uid */
1577                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1578                 qi->lqi_space      = -1;
1579                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1580                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1581                         rc = 0;
1582                 if (rc)
1583                         RETURN(rc);
1584
1585                 /* block accounting */
1586                 qi->lqi_is_blk = true;
1587
1588                 /* more blocks for the new owner ... */
1589                 qi->lqi_id.qid_uid = attr->la_uid;
1590                 qi->lqi_space      = bspace;
1591                 allocated = (attr->la_uid == 0) ? true : false;
1592                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1593                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1594                         rc = 0;
1595                 if (rc)
1596                         RETURN(rc);
1597
1598                 /* and finally less blocks for the current owner */
1599                 qi->lqi_id.qid_uid = obj->oo_inode->i_uid;
1600                 qi->lqi_space      = -bspace;
1601                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1602                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1603                         rc = 0;
1604                 if (rc)
1605                         RETURN(rc);
1606         }
1607
1608         if (attr->la_valid & LA_GID &&
1609             attr->la_gid != obj->oo_inode->i_gid) {
1610                 qi->lqi_type = GRPQUOTA;
1611
1612                 /* inode accounting */
1613                 qi->lqi_is_blk = false;
1614
1615                 /* one more inode for the new group owner ... */
1616                 qi->lqi_id.qid_gid = attr->la_gid;
1617                 qi->lqi_space      = 1;
1618                 allocated = (attr->la_gid == 0) ? true : false;
1619                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1620                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1621                         rc = 0;
1622                 if (rc)
1623                         RETURN(rc);
1624
1625                 /* and one less inode for the current gid */
1626                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1627                 qi->lqi_space      = -1;
1628                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1629                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1630                         rc = 0;
1631                 if (rc)
1632                         RETURN(rc);
1633
1634                 /* block accounting */
1635                 qi->lqi_is_blk = true;
1636
1637                 /* more blocks for the new owner ... */
1638                 qi->lqi_id.qid_gid = attr->la_gid;
1639                 qi->lqi_space      = bspace;
1640                 allocated = (attr->la_gid == 0) ? true : false;
1641                 rc = osd_declare_qid(env, oh, qi, allocated, NULL);
1642                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1643                         rc = 0;
1644                 if (rc)
1645                         RETURN(rc);
1646
1647                 /* and finally less blocks for the current owner */
1648                 qi->lqi_id.qid_gid = obj->oo_inode->i_gid;
1649                 qi->lqi_space      = -bspace;
1650                 rc = osd_declare_qid(env, oh, qi, true, NULL);
1651                 if (rc == -EDQUOT || rc == -EINPROGRESS)
1652                         rc = 0;
1653                 if (rc)
1654                         RETURN(rc);
1655         }
1656
1657         RETURN(rc);
1658 }
1659
1660 static int osd_inode_setattr(const struct lu_env *env,
1661                              struct inode *inode, const struct lu_attr *attr)
1662 {
1663         __u64 bits;
1664
1665         bits = attr->la_valid;
1666
1667         if (bits & LA_ATIME)
1668                 inode->i_atime  = *osd_inode_time(env, inode, attr->la_atime);
1669         if (bits & LA_CTIME)
1670                 inode->i_ctime  = *osd_inode_time(env, inode, attr->la_ctime);
1671         if (bits & LA_MTIME)
1672                 inode->i_mtime  = *osd_inode_time(env, inode, attr->la_mtime);
1673         if (bits & LA_SIZE) {
1674                 LDISKFS_I(inode)->i_disksize = attr->la_size;
1675                 i_size_write(inode, attr->la_size);
1676         }
1677
1678 #if 0
1679         /* OSD should not change "i_blocks" which is used by quota.
1680          * "i_blocks" should be changed by ldiskfs only. */
1681         if (bits & LA_BLOCKS)
1682                 inode->i_blocks = attr->la_blocks;
1683 #endif
1684         if (bits & LA_MODE)
1685                 inode->i_mode   = (inode->i_mode & S_IFMT) |
1686                         (attr->la_mode & ~S_IFMT);
1687         if (bits & LA_UID)
1688                 inode->i_uid    = attr->la_uid;
1689         if (bits & LA_GID)
1690                 inode->i_gid    = attr->la_gid;
1691         if (bits & LA_NLINK)
1692                 set_nlink(inode, attr->la_nlink);
1693         if (bits & LA_RDEV)
1694                 inode->i_rdev   = attr->la_rdev;
1695
1696         if (bits & LA_FLAGS) {
1697                 /* always keep S_NOCMTIME */
1698                 inode->i_flags = ll_ext_to_inode_flags(attr->la_flags) |
1699                                  S_NOCMTIME;
1700         }
1701         return 0;
1702 }
1703
1704 static int osd_quota_transfer(struct inode *inode, const struct lu_attr *attr)
1705 {
1706         if ((attr->la_valid & LA_UID && attr->la_uid != inode->i_uid) ||
1707             (attr->la_valid & LA_GID && attr->la_gid != inode->i_gid)) {
1708                 struct iattr    iattr;
1709                 int             rc;
1710
1711                 iattr.ia_valid = 0;
1712                 if (attr->la_valid & LA_UID)
1713                         iattr.ia_valid |= ATTR_UID;
1714                 if (attr->la_valid & LA_GID)
1715                         iattr.ia_valid |= ATTR_GID;
1716                 iattr.ia_uid = attr->la_uid;
1717                 iattr.ia_gid = attr->la_gid;
1718
1719                 rc = ll_vfs_dq_transfer(inode, &iattr);
1720                 if (rc) {
1721                         CERROR("%s: quota transfer failed: rc = %d. Is quota "
1722                                "enforcement enabled on the ldiskfs filesystem?",
1723                                inode->i_sb->s_id, rc);
1724                         return rc;
1725                 }
1726         }
1727         return 0;
1728 }
1729
1730 static int osd_attr_set(const struct lu_env *env,
1731                         struct dt_object *dt,
1732                         const struct lu_attr *attr,
1733                         struct thandle *handle,
1734                         struct lustre_capa *capa)
1735 {
1736         struct osd_object *obj = osd_dt_obj(dt);
1737         struct inode      *inode;
1738         int rc;
1739
1740         LASSERT(handle != NULL);
1741         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
1742         LASSERT(osd_invariant(obj));
1743
1744         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
1745                 return -EACCES;
1746
1747         osd_trans_exec_op(env, handle, OSD_OT_ATTR_SET);
1748
1749         if (OBD_FAIL_CHECK(OBD_FAIL_OSD_FID_MAPPING)) {
1750                 struct osd_thread_info  *oti  = osd_oti_get(env);
1751                 const struct lu_fid     *fid0 = lu_object_fid(&dt->do_lu);
1752                 struct lu_fid           *fid1 = &oti->oti_fid;
1753                 struct osd_inode_id     *id   = &oti->oti_id;
1754                 struct iam_path_descr   *ipd;
1755                 struct iam_container    *bag;
1756                 struct osd_thandle      *oh;
1757                 int                      rc;
1758
1759                 fid_cpu_to_be(fid1, fid0);
1760                 memset(id, 1, sizeof(*id));
1761                 bag = &osd_fid2oi(osd_dev(dt->do_lu.lo_dev),
1762                                   fid0)->oi_dir.od_container;
1763                 ipd = osd_idx_ipd_get(env, bag);
1764                 if (unlikely(ipd == NULL))
1765                         RETURN(-ENOMEM);
1766
1767                 oh = container_of0(handle, struct osd_thandle, ot_super);
1768                 rc = iam_update(oh->ot_handle, bag, (const struct iam_key *)fid1,
1769                                 (const struct iam_rec *)id, ipd);
1770                 osd_ipd_put(env, bag, ipd);
1771                 return(rc > 0 ? 0 : rc);
1772         }
1773
1774         inode = obj->oo_inode;
1775         ll_vfs_dq_init(inode);
1776
1777         rc = osd_quota_transfer(inode, attr);
1778         if (rc)
1779                 return rc;
1780
1781         spin_lock(&obj->oo_guard);
1782         rc = osd_inode_setattr(env, inode, attr);
1783         spin_unlock(&obj->oo_guard);
1784
1785         if (!rc)
1786                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
1787         return rc;
1788 }
1789
1790 struct dentry *osd_child_dentry_get(const struct lu_env *env,
1791                                     struct osd_object *obj,
1792                                     const char *name, const int namelen)
1793 {
1794         return osd_child_dentry_by_inode(env, obj->oo_inode, name, namelen);
1795 }
1796
1797 static int osd_mkfile(struct osd_thread_info *info, struct osd_object *obj,
1798                       cfs_umode_t mode,
1799                       struct dt_allocation_hint *hint,
1800                       struct thandle *th)
1801 {
1802         int result;
1803         struct osd_device  *osd = osd_obj2dev(obj);
1804         struct osd_thandle *oth;
1805         struct dt_object   *parent = NULL;
1806         struct inode       *inode;
1807
1808         LINVRNT(osd_invariant(obj));
1809         LASSERT(obj->oo_inode == NULL);
1810         LASSERT(obj->oo_hl_head == NULL);
1811
1812         if (S_ISDIR(mode) && ldiskfs_pdo) {
1813                 obj->oo_hl_head =ldiskfs_htree_lock_head_alloc(HTREE_HBITS_DEF);
1814                 if (obj->oo_hl_head == NULL)
1815                         return -ENOMEM;
1816         }
1817
1818         oth = container_of(th, struct osd_thandle, ot_super);
1819         LASSERT(oth->ot_handle->h_transaction != NULL);
1820
1821         if (hint && hint->dah_parent)
1822                 parent = hint->dah_parent;
1823
1824         inode = ldiskfs_create_inode(oth->ot_handle,
1825                                      parent ? osd_dt_obj(parent)->oo_inode :
1826                                               osd_sb(osd)->s_root->d_inode,
1827                                      mode);
1828         if (!IS_ERR(inode)) {
1829                 /* Do not update file c/mtime in ldiskfs.
1830                  * NB: don't need any lock because no contention at this
1831                  * early stage */
1832                 inode->i_flags |= S_NOCMTIME;
1833
1834                 /* For new created object, it must be consistent,
1835                  * and it is unnecessary to scrub against it. */
1836                 ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NOSCRUB);
1837                 obj->oo_inode = inode;
1838                 result = 0;
1839         } else {
1840                 if (obj->oo_hl_head != NULL) {
1841                         ldiskfs_htree_lock_head_free(obj->oo_hl_head);
1842                         obj->oo_hl_head = NULL;
1843                 }
1844                 result = PTR_ERR(inode);
1845         }
1846         LINVRNT(osd_invariant(obj));
1847         return result;
1848 }
1849
1850 enum {
1851         OSD_NAME_LEN = 255
1852 };
1853
1854 static int osd_mkdir(struct osd_thread_info *info, struct osd_object *obj,
1855                      struct lu_attr *attr,
1856                      struct dt_allocation_hint *hint,
1857                      struct dt_object_format *dof,
1858                      struct thandle *th)
1859 {
1860         int result;
1861         struct osd_thandle *oth;
1862         __u32 mode = (attr->la_mode & (S_IFMT | S_IRWXUGO | S_ISVTX));
1863
1864         LASSERT(S_ISDIR(attr->la_mode));
1865
1866         oth = container_of(th, struct osd_thandle, ot_super);
1867         LASSERT(oth->ot_handle->h_transaction != NULL);
1868         result = osd_mkfile(info, obj, mode, hint, th);
1869
1870         return result;
1871 }
1872
1873 static int osd_mk_index(struct osd_thread_info *info, struct osd_object *obj,
1874                         struct lu_attr *attr,
1875                         struct dt_allocation_hint *hint,
1876                         struct dt_object_format *dof,
1877                         struct thandle *th)
1878 {
1879         int result;
1880         struct osd_thandle *oth;
1881         const struct dt_index_features *feat = dof->u.dof_idx.di_feat;
1882
1883         __u32 mode = (attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX));
1884
1885         LASSERT(S_ISREG(attr->la_mode));
1886
1887         oth = container_of(th, struct osd_thandle, ot_super);
1888         LASSERT(oth->ot_handle->h_transaction != NULL);
1889
1890         result = osd_mkfile(info, obj, mode, hint, th);
1891         if (result == 0) {
1892                 LASSERT(obj->oo_inode != NULL);
1893                 if (feat->dif_flags & DT_IND_VARKEY)
1894                         result = iam_lvar_create(obj->oo_inode,
1895                                                  feat->dif_keysize_max,
1896                                                  feat->dif_ptrsize,
1897                                                  feat->dif_recsize_max,
1898                                                  oth->ot_handle);
1899                 else
1900                         result = iam_lfix_create(obj->oo_inode,
1901                                                  feat->dif_keysize_max,
1902                                                  feat->dif_ptrsize,
1903                                                  feat->dif_recsize_max,
1904                                                  oth->ot_handle);
1905
1906         }
1907         return result;
1908 }
1909
1910 static int osd_mkreg(struct osd_thread_info *info, struct osd_object *obj,
1911                      struct lu_attr *attr,
1912                      struct dt_allocation_hint *hint,
1913                      struct dt_object_format *dof,
1914                      struct thandle *th)
1915 {
1916         LASSERT(S_ISREG(attr->la_mode));
1917         return osd_mkfile(info, obj, (attr->la_mode &
1918                                (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1919 }
1920
1921 static int osd_mksym(struct osd_thread_info *info, struct osd_object *obj,
1922                      struct lu_attr *attr,
1923                      struct dt_allocation_hint *hint,
1924                      struct dt_object_format *dof,
1925                      struct thandle *th)
1926 {
1927         LASSERT(S_ISLNK(attr->la_mode));
1928         return osd_mkfile(info, obj, (attr->la_mode &
1929                               (S_IFMT | S_IALLUGO | S_ISVTX)), hint, th);
1930 }
1931
1932 static int osd_mknod(struct osd_thread_info *info, struct osd_object *obj,
1933                      struct lu_attr *attr,
1934                      struct dt_allocation_hint *hint,
1935                      struct dt_object_format *dof,
1936                      struct thandle *th)
1937 {
1938         cfs_umode_t mode = attr->la_mode & (S_IFMT | S_IALLUGO | S_ISVTX);
1939         int result;
1940
1941         LINVRNT(osd_invariant(obj));
1942         LASSERT(obj->oo_inode == NULL);
1943         LASSERT(S_ISCHR(mode) || S_ISBLK(mode) ||
1944                 S_ISFIFO(mode) || S_ISSOCK(mode));
1945
1946         result = osd_mkfile(info, obj, mode, hint, th);
1947         if (result == 0) {
1948                 LASSERT(obj->oo_inode != NULL);
1949                 /*
1950                  * This inode should be marked dirty for i_rdev.  Currently
1951                  * that is done in the osd_attr_init().
1952                  */
1953                 init_special_inode(obj->oo_inode, obj->oo_inode->i_mode,
1954                                    attr->la_rdev);
1955         }
1956         LINVRNT(osd_invariant(obj));
1957         return result;
1958 }
1959
1960 typedef int (*osd_obj_type_f)(struct osd_thread_info *, struct osd_object *,
1961                               struct lu_attr *,
1962                               struct dt_allocation_hint *hint,
1963                               struct dt_object_format *dof,
1964                               struct thandle *);
1965
1966 static osd_obj_type_f osd_create_type_f(enum dt_format_type type)
1967 {
1968         osd_obj_type_f result;
1969
1970         switch (type) {
1971         case DFT_DIR:
1972                 result = osd_mkdir;
1973                 break;
1974         case DFT_REGULAR:
1975                 result = osd_mkreg;
1976                 break;
1977         case DFT_SYM:
1978                 result = osd_mksym;
1979                 break;
1980         case DFT_NODE:
1981                 result = osd_mknod;
1982                 break;
1983         case DFT_INDEX:
1984                 result = osd_mk_index;
1985                 break;
1986
1987         default:
1988                 LBUG();
1989                 break;
1990         }
1991         return result;
1992 }
1993
1994
1995 static void osd_ah_init(const struct lu_env *env, struct dt_allocation_hint *ah,
1996                         struct dt_object *parent, struct dt_object *child,
1997                         cfs_umode_t child_mode)
1998 {
1999         LASSERT(ah);
2000
2001         memset(ah, 0, sizeof(*ah));
2002         ah->dah_parent = parent;
2003         ah->dah_mode = child_mode;
2004 }
2005
2006 static void osd_attr_init(struct osd_thread_info *info, struct osd_object *obj,
2007                           struct lu_attr *attr, struct dt_object_format *dof)
2008 {
2009         struct inode   *inode = obj->oo_inode;
2010         __u64           valid = attr->la_valid;
2011         int             result;
2012
2013         attr->la_valid &= ~(LA_TYPE | LA_MODE);
2014
2015         if (dof->dof_type != DFT_NODE)
2016                 attr->la_valid &= ~LA_RDEV;
2017         if ((valid & LA_ATIME) && (attr->la_atime == LTIME_S(inode->i_atime)))
2018                 attr->la_valid &= ~LA_ATIME;
2019         if ((valid & LA_CTIME) && (attr->la_ctime == LTIME_S(inode->i_ctime)))
2020                 attr->la_valid &= ~LA_CTIME;
2021         if ((valid & LA_MTIME) && (attr->la_mtime == LTIME_S(inode->i_mtime)))
2022                 attr->la_valid &= ~LA_MTIME;
2023
2024         result = osd_quota_transfer(inode, attr);
2025         if (result)
2026                 return;
2027
2028         if (attr->la_valid != 0) {
2029                 result = osd_inode_setattr(info->oti_env, inode, attr);
2030                 /*
2031                  * The osd_inode_setattr() should always succeed here.  The
2032                  * only error that could be returned is EDQUOT when we are
2033                  * trying to change the UID or GID of the inode. However, this
2034                  * should not happen since quota enforcement is no longer
2035                  * enabled on ldiskfs (lquota takes care of it).
2036                  */
2037                 LASSERTF(result == 0, "%d", result);
2038                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2039         }
2040
2041         attr->la_valid = valid;
2042 }
2043
2044 /**
2045  * Helper function for osd_object_create()
2046  *
2047  * \retval 0, on success
2048  */
2049 static int __osd_object_create(struct osd_thread_info *info,
2050                                struct osd_object *obj, struct lu_attr *attr,
2051                                struct dt_allocation_hint *hint,
2052                                struct dt_object_format *dof,
2053                                struct thandle *th)
2054 {
2055         int     result;
2056         __u32   umask;
2057
2058         /* we drop umask so that permissions we pass are not affected */
2059         umask = current->fs->umask;
2060         current->fs->umask = 0;
2061
2062         result = osd_create_type_f(dof->dof_type)(info, obj, attr, hint, dof,
2063                                                   th);
2064         if (result == 0) {
2065                 osd_attr_init(info, obj, attr, dof);
2066                 osd_object_init0(obj);
2067                 /* bz 24037 */
2068                 if (obj->oo_inode && (obj->oo_inode->i_state & I_NEW))
2069                         unlock_new_inode(obj->oo_inode);
2070         }
2071
2072         /* restore previous umask value */
2073         current->fs->umask = umask;
2074
2075         return result;
2076 }
2077
2078 /**
2079  * Helper function for osd_object_create()
2080  *
2081  * \retval 0, on success
2082  */
2083 static int __osd_oi_insert(const struct lu_env *env, struct osd_object *obj,
2084                            const struct lu_fid *fid, struct thandle *th)
2085 {
2086         struct osd_thread_info *info = osd_oti_get(env);
2087         struct osd_inode_id    *id   = &info->oti_id;
2088         struct osd_device      *osd  = osd_obj2dev(obj);
2089
2090         LASSERT(obj->oo_inode != NULL);
2091
2092         osd_id_gen(id, obj->oo_inode->i_ino, obj->oo_inode->i_generation);
2093         return osd_oi_insert(info, osd, fid, id, th, OI_CHECK_FLD);
2094 }
2095
2096 int osd_fld_lookup(const struct lu_env *env, struct osd_device *osd,
2097                    const struct lu_fid *fid, struct lu_seq_range *range)
2098 {
2099         struct seq_server_site  *ss = osd_seq_site(osd);
2100         int                     rc;
2101
2102         if (fid_is_idif(fid)) {
2103                 fld_range_set_ost(range);
2104                 range->lsr_index = fid_idif_ost_idx(fid);
2105                 return 0;
2106         }
2107
2108         if (!fid_seq_in_fldb(fid_seq(fid))) {
2109                 fld_range_set_mdt(range);
2110                 if (ss != NULL)
2111                         /* FIXME: If ss is NULL, it suppose not get lsr_index
2112                          * at all */
2113                         range->lsr_index = ss->ss_node_id;
2114                 return 0;
2115         }
2116
2117         LASSERT(ss != NULL);
2118         fld_range_set_any(range);
2119         rc = fld_server_lookup(env, ss->ss_server_fld, fid_seq(fid), range);
2120         if (rc != 0) {
2121                 CERROR("%s: cannot find FLD range for "DFID": rc = %d\n",
2122                        osd_name(osd), PFID(fid), rc);
2123         }
2124         return rc;
2125 }
2126
2127 /*
2128  * Concurrency: no external locking is necessary.
2129  */
2130 static int osd_declare_object_create(const struct lu_env *env,
2131                                      struct dt_object *dt,
2132                                      struct lu_attr *attr,
2133                                      struct dt_allocation_hint *hint,
2134                                      struct dt_object_format *dof,
2135                                      struct thandle *handle)
2136 {
2137         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
2138         struct osd_thandle      *oh;
2139         int                      rc;
2140         ENTRY;
2141
2142         LASSERT(handle != NULL);
2143
2144         oh = container_of0(handle, struct osd_thandle, ot_super);
2145         LASSERT(oh->ot_handle == NULL);
2146
2147         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
2148                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
2149         if (!fid_is_on_ost(osd_oti_get(env), osd_dt_dev(handle->th_dev),
2150                            lu_object_fid(&dt->do_lu), OI_CHECK_FLD))
2151                 /* Reuse idle OI block may cause additional one OI block
2152                  * to be changed. */
2153                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2154                                 osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
2155
2156         /* If this is directory, then we expect . and .. to be inserted as
2157          * well. The one directory block always needs to be created for the
2158          * directory, so we could use DTO_WRITE_BASE here (GDT, block bitmap,
2159          * block), there is no danger of needing a tree for the first block.
2160          */
2161         if (attr && S_ISDIR(attr->la_mode)) {
2162                 osd_trans_declare_op(env, oh, OSD_OT_INSERT,
2163                                      osd_dto_credits_noquota[DTO_WRITE_BASE]);
2164                 osd_trans_declare_op(env, oh, OSD_OT_INSERT, 0);
2165         }
2166
2167         if (!attr)
2168                 RETURN(0);
2169
2170         rc = osd_declare_inode_qid(env, attr->la_uid, attr->la_gid, 1, oh,
2171                                    false, false, NULL, false);
2172         if (rc != 0)
2173                 RETURN(rc);
2174
2175         /* It does fld look up inside declare, and the result will be
2176          * added to fld cache, so the following fld lookup inside insert
2177          * does not need send RPC anymore, so avoid send rpc with holding
2178          * transaction */
2179         if (fid_is_norm(lu_object_fid(&dt->do_lu)) &&
2180                 !fid_is_last_id(lu_object_fid(&dt->do_lu)))
2181                 osd_fld_lookup(env, osd_dt_dev(handle->th_dev),
2182                                lu_object_fid(&dt->do_lu), range);
2183
2184
2185         RETURN(rc);
2186 }
2187
2188 static int osd_object_create(const struct lu_env *env, struct dt_object *dt,
2189                              struct lu_attr *attr,
2190                              struct dt_allocation_hint *hint,
2191                              struct dt_object_format *dof,
2192                              struct thandle *th)
2193 {
2194         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2195         struct osd_object      *obj    = osd_dt_obj(dt);
2196         struct osd_thread_info *info   = osd_oti_get(env);
2197         int result;
2198
2199         ENTRY;
2200
2201         LINVRNT(osd_invariant(obj));
2202         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2203         LASSERT(osd_write_locked(env, obj));
2204         LASSERT(th != NULL);
2205
2206         if (unlikely(fid_is_acct(fid)))
2207                 /* Quota files can't be created from the kernel any more,
2208                  * 'tune2fs -O quota' will take care of creating them */
2209                 RETURN(-EPERM);
2210
2211         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2212         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2213
2214         result = __osd_object_create(info, obj, attr, hint, dof, th);
2215         if (result == 0)
2216                 result = __osd_oi_insert(env, obj, fid, th);
2217
2218         LASSERT(ergo(result == 0,
2219                      dt_object_exists(dt) && !dt_object_remote(dt)));
2220
2221         LASSERT(osd_invariant(obj));
2222         RETURN(result);
2223 }
2224
2225 /**
2226  * Called to destroy on-disk representation of the object
2227  *
2228  * Concurrency: must be locked
2229  */
2230 static int osd_declare_object_destroy(const struct lu_env *env,
2231                                       struct dt_object *dt,
2232                                       struct thandle *th)
2233 {
2234         struct osd_object  *obj = osd_dt_obj(dt);
2235         struct inode       *inode = obj->oo_inode;
2236         struct osd_thandle *oh;
2237         int                 rc;
2238         ENTRY;
2239
2240         oh = container_of0(th, struct osd_thandle, ot_super);
2241         LASSERT(oh->ot_handle == NULL);
2242         LASSERT(inode);
2243
2244         osd_trans_declare_op(env, oh, OSD_OT_DESTROY,
2245                              osd_dto_credits_noquota[DTO_OBJECT_DELETE]);
2246         /* Recycle idle OI leaf may cause additional three OI blocks
2247          * to be changed. */
2248         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
2249                              osd_dto_credits_noquota[DTO_INDEX_DELETE] + 3);
2250         /* one less inode */
2251         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, -1, oh,
2252                                    false, true, NULL, false);
2253         if (rc)
2254                 RETURN(rc);
2255         /* data to be truncated */
2256         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
2257                                    true, true, NULL, false);
2258         RETURN(rc);
2259 }
2260
2261 static int osd_object_destroy(const struct lu_env *env,
2262                               struct dt_object *dt,
2263                               struct thandle *th)
2264 {
2265         const struct lu_fid    *fid = lu_object_fid(&dt->do_lu);
2266         struct osd_object      *obj = osd_dt_obj(dt);
2267         struct inode           *inode = obj->oo_inode;
2268         struct osd_device      *osd = osd_obj2dev(obj);
2269         struct osd_thandle     *oh;
2270         int                     result;
2271         ENTRY;
2272
2273         oh = container_of0(th, struct osd_thandle, ot_super);
2274         LASSERT(oh->ot_handle);
2275         LASSERT(inode);
2276         LASSERT(!lu_object_is_dying(dt->do_lu.lo_header));
2277
2278         if (unlikely(fid_is_acct(fid)))
2279                 RETURN(-EPERM);
2280
2281         if (S_ISDIR(inode->i_mode)) {
2282                 LASSERT(osd_inode_unlinked(inode) || inode->i_nlink == 1);
2283                 /* it will check/delete the inode from remote parent,
2284                  * how to optimize it? unlink performance impaction XXX */
2285                 result = osd_delete_from_remote_parent(env, osd, obj, oh);
2286                 if (result != 0 && result != -ENOENT) {
2287                         CERROR("%s: delete inode "DFID": rc = %d\n",
2288                                osd_name(osd), PFID(fid), result);
2289                 }
2290                 spin_lock(&obj->oo_guard);
2291                 clear_nlink(inode);
2292                 spin_unlock(&obj->oo_guard);
2293                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2294         }
2295
2296         osd_trans_exec_op(env, th, OSD_OT_DESTROY);
2297
2298         result = osd_oi_delete(osd_oti_get(env), osd, fid, th, OI_CHECK_FLD);
2299
2300         /* XXX: add to ext3 orphan list */
2301         /* rc = ext3_orphan_add(handle_t *handle, struct inode *inode) */
2302
2303         /* not needed in the cache anymore */
2304         set_bit(LU_OBJECT_HEARD_BANSHEE, &dt->do_lu.lo_header->loh_flags);
2305
2306         RETURN(0);
2307 }
2308
2309 /**
2310  * Put the fid into lustre_mdt_attrs, and then place the structure
2311  * inode's ea. This fid should not be altered during the life time
2312  * of the inode.
2313  *
2314  * \retval +ve, on success
2315  * \retval -ve, on error
2316  *
2317  * FIXME: It is good to have/use ldiskfs_xattr_set_handle() here
2318  */
2319 int osd_ea_fid_set(struct osd_thread_info *info, struct inode *inode,
2320                    const struct lu_fid *fid, __u32 compat, __u32 incompat)
2321 {
2322         struct lustre_mdt_attrs *lma = &info->oti_mdt_attrs;
2323         int                      rc;
2324         ENTRY;
2325
2326         if (OBD_FAIL_CHECK(OBD_FAIL_FID_INLMA))
2327                 RETURN(0);
2328
2329         lustre_lma_init(lma, fid, compat, incompat);
2330         lustre_lma_swab(lma);
2331
2332         rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma, sizeof(*lma),
2333                              XATTR_CREATE);
2334         /* LMA may already exist, but we need to check that all the
2335          * desired compat/incompat flags have been added. */
2336         if (unlikely(rc == -EEXIST)) {
2337                 if (compat == 0 && incompat == 0)
2338                         RETURN(0);
2339
2340                 rc = __osd_xattr_get(inode, &info->oti_obj_dentry,
2341                                      XATTR_NAME_LMA, info->oti_mdt_attrs_old,
2342                                      LMA_OLD_SIZE);
2343                 if (rc <= 0)
2344                         RETURN(-EINVAL);
2345
2346                 lustre_lma_swab(lma);
2347                 if (!(~lma->lma_compat & compat) &&
2348                     !(~lma->lma_incompat & incompat))
2349                         RETURN(0);
2350
2351                 lma->lma_compat |= compat;
2352                 lma->lma_incompat |= incompat;
2353                 lustre_lma_swab(lma);
2354                 rc = __osd_xattr_set(info, inode, XATTR_NAME_LMA, lma,
2355                                      sizeof(*lma), XATTR_REPLACE);
2356         }
2357
2358         RETURN(rc);
2359 }
2360
2361 /**
2362  * ldiskfs supports fid in dirent, it is passed in dentry->d_fsdata.
2363  * lustre 1.8 also uses d_fsdata for passing other info to ldiskfs.
2364  * To have compatilibility with 1.8 ldiskfs driver we need to have
2365  * magic number at start of fid data.
2366  * \ldiskfs_dentry_param is used only to pass fid from osd to ldiskfs.
2367  * its inmemory API.
2368  */
2369 void osd_get_ldiskfs_dirent_param(struct ldiskfs_dentry_param *param,
2370                                   const struct dt_rec *fid)
2371 {
2372         if (!fid_is_namespace_visible((const struct lu_fid *)fid) ||
2373             OBD_FAIL_CHECK(OBD_FAIL_FID_IGIF)) {
2374                 param->edp_magic = 0;
2375                 return;
2376         }
2377
2378         param->edp_magic = LDISKFS_LUFID_MAGIC;
2379         param->edp_len =  sizeof(struct lu_fid) + 1;
2380         fid_cpu_to_be((struct lu_fid *)param->edp_data, (struct lu_fid *)fid);
2381 }
2382
2383 /**
2384  * Try to read the fid from inode ea into dt_rec.
2385  *
2386  * \param fid object fid.
2387  *
2388  * \retval 0 on success
2389  */
2390 static int osd_ea_fid_get(const struct lu_env *env, struct osd_object *obj,
2391                           __u32 ino, struct lu_fid *fid,
2392                           struct osd_inode_id *id)
2393 {
2394         struct osd_thread_info *info  = osd_oti_get(env);
2395         struct inode           *inode;
2396         ENTRY;
2397
2398         osd_id_gen(id, ino, OSD_OII_NOGEN);
2399         inode = osd_iget_fid(info, osd_obj2dev(obj), id, fid);
2400         if (IS_ERR(inode))
2401                 RETURN(PTR_ERR(inode));
2402
2403         iput(inode);
2404         RETURN(0);
2405 }
2406
2407 static int osd_add_dot_dotdot_internal(struct osd_thread_info *info,
2408                                         struct inode *dir,
2409                                         struct inode  *parent_dir,
2410                                         const struct dt_rec *dot_fid,
2411                                         const struct dt_rec *dot_dot_fid,
2412                                         struct osd_thandle *oth)
2413 {
2414         struct ldiskfs_dentry_param *dot_ldp;
2415         struct ldiskfs_dentry_param *dot_dot_ldp;
2416
2417         dot_dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp2;
2418         osd_get_ldiskfs_dirent_param(dot_dot_ldp, dot_dot_fid);
2419
2420         dot_ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
2421         dot_ldp->edp_magic = 0;
2422         return ldiskfs_add_dot_dotdot(oth->ot_handle, parent_dir,
2423                                         dir, dot_ldp, dot_dot_ldp);
2424 }
2425
2426 /**
2427  * Create an local agent inode for remote entry
2428  */
2429 static struct inode *osd_create_local_agent_inode(const struct lu_env *env,
2430                                                   struct osd_device *osd,
2431                                                   struct osd_object *pobj,
2432                                                   const struct lu_fid *fid,
2433                                                   struct thandle *th)
2434 {
2435         struct osd_thread_info  *info = osd_oti_get(env);
2436         struct inode            *local;
2437         struct osd_thandle      *oh;
2438         int                     rc;
2439         ENTRY;
2440
2441         LASSERT(th);
2442         oh = container_of(th, struct osd_thandle, ot_super);
2443         LASSERT(oh->ot_handle->h_transaction != NULL);
2444
2445         /* FIXME: Insert index api needs to know the mode of
2446          * the remote object. Just use S_IFDIR for now */
2447         local = ldiskfs_create_inode(oh->ot_handle, pobj->oo_inode, S_IFDIR);
2448         if (IS_ERR(local)) {
2449                 CERROR("%s: create local error %d\n", osd_name(osd),
2450                        (int)PTR_ERR(local));
2451                 RETURN(local);
2452         }
2453
2454         /* Set special LMA flag for local agent inode */
2455         rc = osd_ea_fid_set(info, local, fid, 0, LMAI_AGENT);
2456         if (rc != 0) {
2457                 CERROR("%s: set LMA for "DFID" remote inode failed: rc = %d\n",
2458                        osd_name(osd), PFID(fid), rc);
2459                 RETURN(ERR_PTR(rc));
2460         }
2461
2462         rc = osd_add_dot_dotdot_internal(info, local, pobj->oo_inode,
2463                 (const struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
2464                 (const struct dt_rec *)fid, oh);
2465         if (rc != 0) {
2466                 CERROR("%s: "DFID" add dot dotdot error: rc = %d\n",
2467                         osd_name(osd), PFID(fid), rc);
2468                 RETURN(ERR_PTR(rc));
2469         }
2470
2471         RETURN(local);
2472 }
2473
2474 /**
2475  * Delete local agent inode for remote entry
2476  */
2477 static int osd_delete_local_agent_inode(const struct lu_env *env,
2478                                         struct osd_device *osd,
2479                                         const struct lu_fid *fid,
2480                                         __u32 ino, struct osd_thandle *oh)
2481 {
2482         struct osd_thread_info  *oti = osd_oti_get(env);
2483         struct osd_inode_id     *id = &oti->oti_id;
2484         struct inode            *inode;
2485         ENTRY;
2486
2487         id->oii_ino = le32_to_cpu(ino);
2488         id->oii_gen = OSD_OII_NOGEN;
2489         inode = osd_iget(oti, osd, id);
2490         if (IS_ERR(inode)) {
2491                 CERROR("%s: iget error "DFID" id %u:%u\n", osd_name(osd),
2492                        PFID(fid), id->oii_ino, id->oii_gen);
2493                 RETURN(PTR_ERR(inode));
2494         }
2495
2496         clear_nlink(inode);
2497         mark_inode_dirty(inode);
2498         CDEBUG(D_INODE, "%s: delete remote inode "DFID" %lu\n",
2499                 osd_name(osd), PFID(fid), inode->i_ino);
2500         iput(inode);
2501         RETURN(0);
2502 }
2503
2504 /**
2505  * OSD layer object create function for interoperability mode (b11826).
2506  * This is mostly similar to osd_object_create(). Only difference being, fid is
2507  * inserted into inode ea here.
2508  *
2509  * \retval   0, on success
2510  * \retval -ve, on error
2511  */
2512 static int osd_object_ea_create(const struct lu_env *env, struct dt_object *dt,
2513                                 struct lu_attr *attr,
2514                                 struct dt_allocation_hint *hint,
2515                                 struct dt_object_format *dof,
2516                                 struct thandle *th)
2517 {
2518         const struct lu_fid    *fid    = lu_object_fid(&dt->do_lu);
2519         struct osd_object      *obj    = osd_dt_obj(dt);
2520         struct osd_thread_info *info   = osd_oti_get(env);
2521         int                     result;
2522
2523         ENTRY;
2524
2525         LASSERT(osd_invariant(obj));
2526         LASSERT(!dt_object_exists(dt) && !dt_object_remote(dt));
2527         LASSERT(osd_write_locked(env, obj));
2528         LASSERT(th != NULL);
2529
2530         if (unlikely(fid_is_acct(fid)))
2531                 /* Quota files can't be created from the kernel any more,
2532                  * 'tune2fs -O quota' will take care of creating them */
2533                 RETURN(-EPERM);
2534
2535         osd_trans_exec_op(env, th, OSD_OT_CREATE);
2536         osd_trans_declare_rb(env, th, OSD_OT_REF_ADD);
2537
2538         result = __osd_object_create(info, obj, attr, hint, dof, th);
2539         if (result == 0)
2540                 result = osd_ea_fid_set(info, obj->oo_inode, fid,
2541                                 fid_is_on_ost(info, osd_obj2dev(obj),
2542                                               fid, OI_CHECK_FLD) ?
2543                                 LMAC_FID_ON_OST : 0, 0);
2544
2545         if (result == 0)
2546                 result = __osd_oi_insert(env, obj, fid, th);
2547
2548         LASSERT(ergo(result == 0,
2549                      dt_object_exists(dt) && !dt_object_remote(dt)));
2550         LINVRNT(osd_invariant(obj));
2551         RETURN(result);
2552 }
2553
2554 static int osd_declare_object_ref_add(const struct lu_env *env,
2555                                       struct dt_object *dt,
2556                                       struct thandle *handle)
2557 {
2558         struct osd_thandle       *oh;
2559
2560         /* it's possible that object doesn't exist yet */
2561         LASSERT(handle != NULL);
2562
2563         oh = container_of0(handle, struct osd_thandle, ot_super);
2564         LASSERT(oh->ot_handle == NULL);
2565
2566         osd_trans_declare_op(env, oh, OSD_OT_REF_ADD,
2567                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2568
2569         return 0;
2570 }
2571
2572 /*
2573  * Concurrency: @dt is write locked.
2574  */
2575 static int osd_object_ref_add(const struct lu_env *env,
2576                               struct dt_object *dt, struct thandle *th)
2577 {
2578         struct osd_object *obj = osd_dt_obj(dt);
2579         struct inode      *inode = obj->oo_inode;
2580         bool               need_dirty = false;
2581         int                rc = 0;
2582
2583         LINVRNT(osd_invariant(obj));
2584         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2585         LASSERT(osd_write_locked(env, obj));
2586         LASSERT(th != NULL);
2587
2588         osd_trans_exec_op(env, th, OSD_OT_REF_ADD);
2589
2590         /* This based on ldiskfs_inc_count(), which is not exported.
2591          *
2592          * The DIR_NLINK feature allows directories to exceed LDISKFS_LINK_MAX
2593          * (65000) subdirectories by storing "1" in i_nlink if the link count
2594          * would otherwise overflow. Directory tranversal tools understand
2595          * that (st_nlink == 1) indicates that the filesystem dose not track
2596          * hard links count on the directory, and will not abort subdirectory
2597          * scanning early once (st_nlink - 2) subdirs have been found.
2598          *
2599          * This also has to properly handle the case of inodes with nlink == 0
2600          * in case they are being linked into the PENDING directory
2601          */
2602         spin_lock(&obj->oo_guard);
2603         if (unlikely(!S_ISDIR(inode->i_mode) &&
2604                      inode->i_nlink >= LDISKFS_LINK_MAX)) {
2605                 /* MDD should have checked this, but good to be safe */
2606                 rc = -EMLINK;
2607         } else if (unlikely(inode->i_nlink == 0 ||
2608                             (S_ISDIR(inode->i_mode) &&
2609                              inode->i_nlink >= LDISKFS_LINK_MAX))) {
2610                 /* inc_nlink from 0 may cause WARN_ON */
2611                 set_nlink(inode, 1);
2612                 need_dirty = true;
2613         } else if (!S_ISDIR(inode->i_mode) ||
2614                    (S_ISDIR(inode->i_mode) && inode->i_nlink >= 2)) {
2615                 inc_nlink(inode);
2616                 need_dirty = true;
2617         } /* else (S_ISDIR(inode->i_mode) && inode->i_nlink == 1) { ; } */
2618
2619         LASSERT(inode->i_nlink <= LDISKFS_LINK_MAX);
2620         spin_unlock(&obj->oo_guard);
2621
2622         if (need_dirty)
2623                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2624
2625         LINVRNT(osd_invariant(obj));
2626
2627         return rc;
2628 }
2629
2630 static int osd_declare_object_ref_del(const struct lu_env *env,
2631                                       struct dt_object *dt,
2632                                       struct thandle *handle)
2633 {
2634         struct osd_thandle *oh;
2635
2636         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2637         LASSERT(handle != NULL);
2638
2639         oh = container_of0(handle, struct osd_thandle, ot_super);
2640         LASSERT(oh->ot_handle == NULL);
2641
2642         osd_trans_declare_op(env, oh, OSD_OT_REF_DEL,
2643                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE]);
2644
2645         return 0;
2646 }
2647
2648 /*
2649  * Concurrency: @dt is write locked.
2650  */
2651 static int osd_object_ref_del(const struct lu_env *env, struct dt_object *dt,
2652                               struct thandle *th)
2653 {
2654         struct osd_object *obj = osd_dt_obj(dt);
2655         struct inode      *inode = obj->oo_inode;
2656
2657         LINVRNT(osd_invariant(obj));
2658         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2659         LASSERT(osd_write_locked(env, obj));
2660         LASSERT(th != NULL);
2661
2662         osd_trans_exec_op(env, th, OSD_OT_REF_DEL);
2663
2664         spin_lock(&obj->oo_guard);
2665         LASSERT(inode->i_nlink > 0);
2666
2667         /* This based on ldiskfs_dec_count(), which is not exported.
2668          *
2669          * If a directory already has nlink == 1, then do not drop the nlink
2670          * count to 0, even temporarily, to avoid race conditions with other
2671          * threads not holding oo_guard seeing i_nlink == 0 in rare cases.
2672          *
2673          * nlink == 1 means the directory has/had > EXT4_LINK_MAX subdirs.
2674          * */
2675         if (!S_ISDIR(inode->i_mode) || inode->i_nlink > 1) {
2676                 drop_nlink(inode);
2677
2678                 spin_unlock(&obj->oo_guard);
2679                 ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2680                 LINVRNT(osd_invariant(obj));
2681         } else {
2682                 spin_unlock(&obj->oo_guard);
2683         }
2684
2685         return 0;
2686 }
2687
2688 /*
2689  * Get the 64-bit version for an inode.
2690  */
2691 static int osd_object_version_get(const struct lu_env *env,
2692                                   struct dt_object *dt, dt_obj_version_t *ver)
2693 {
2694         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2695
2696         CDEBUG(D_INODE, "Get version "LPX64" for inode %lu\n",
2697                LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2698         *ver = LDISKFS_I(inode)->i_fs_version;
2699         return 0;
2700 }
2701
2702 /*
2703  * Concurrency: @dt is read locked.
2704  */
2705 static int osd_xattr_get(const struct lu_env *env, struct dt_object *dt,
2706                          struct lu_buf *buf, const char *name,
2707                          struct lustre_capa *capa)
2708 {
2709         struct osd_object      *obj    = osd_dt_obj(dt);
2710         struct inode           *inode  = obj->oo_inode;
2711         struct osd_thread_info *info   = osd_oti_get(env);
2712         struct dentry          *dentry = &info->oti_obj_dentry;
2713
2714         /* version get is not real XATTR but uses xattr API */
2715         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2716                 /* for version we are just using xattr API but change inode
2717                  * field instead */
2718                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2719                 osd_object_version_get(env, dt, buf->lb_buf);
2720                 return sizeof(dt_obj_version_t);
2721         }
2722
2723         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2724         LASSERT(inode->i_op != NULL && inode->i_op->getxattr != NULL);
2725
2726         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2727                 return -EACCES;
2728
2729         return __osd_xattr_get(inode, dentry, name, buf->lb_buf, buf->lb_len);
2730 }
2731
2732
2733 static int osd_declare_xattr_set(const struct lu_env *env,
2734                                  struct dt_object *dt,
2735                                  const struct lu_buf *buf, const char *name,
2736                                  int fl, struct thandle *handle)
2737 {
2738         struct osd_thandle *oh;
2739
2740         LASSERT(handle != NULL);
2741
2742         oh = container_of0(handle, struct osd_thandle, ot_super);
2743         LASSERT(oh->ot_handle == NULL);
2744
2745         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2746                              strcmp(name, XATTR_NAME_VERSION) == 0 ?
2747                              osd_dto_credits_noquota[DTO_ATTR_SET_BASE] :
2748                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2749
2750         return 0;
2751 }
2752
2753 /*
2754  * Set the 64-bit version for object
2755  */
2756 static void osd_object_version_set(const struct lu_env *env,
2757                                    struct dt_object *dt,
2758                                    dt_obj_version_t *new_version)
2759 {
2760         struct inode *inode = osd_dt_obj(dt)->oo_inode;
2761
2762         CDEBUG(D_INODE, "Set version "LPX64" (old "LPX64") for inode %lu\n",
2763                *new_version, LDISKFS_I(inode)->i_fs_version, inode->i_ino);
2764
2765         LDISKFS_I(inode)->i_fs_version = *new_version;
2766         /** Version is set after all inode operations are finished,
2767          *  so we should mark it dirty here */
2768         ll_dirty_inode(inode, I_DIRTY_DATASYNC);
2769 }
2770
2771 /*
2772  * Concurrency: @dt is write locked.
2773  */
2774 static int osd_xattr_set(const struct lu_env *env, struct dt_object *dt,
2775                          const struct lu_buf *buf, const char *name, int fl,
2776                          struct thandle *handle, struct lustre_capa *capa)
2777 {
2778         struct osd_object      *obj      = osd_dt_obj(dt);
2779         struct inode           *inode    = obj->oo_inode;
2780         struct osd_thread_info *info     = osd_oti_get(env);
2781         int                     fs_flags = 0;
2782         ENTRY;
2783
2784         LASSERT(handle != NULL);
2785
2786         /* version set is not real XATTR */
2787         if (strcmp(name, XATTR_NAME_VERSION) == 0) {
2788                 /* for version we are just using xattr API but change inode
2789                  * field instead */
2790                 LASSERT(buf->lb_len == sizeof(dt_obj_version_t));
2791                 osd_object_version_set(env, dt, buf->lb_buf);
2792                 return sizeof(dt_obj_version_t);
2793         }
2794
2795         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2796                 return -EACCES;
2797
2798         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2799         if (fl & LU_XATTR_REPLACE)
2800                 fs_flags |= XATTR_REPLACE;
2801
2802         if (fl & LU_XATTR_CREATE)
2803                 fs_flags |= XATTR_CREATE;
2804
2805         return __osd_xattr_set(info, inode, name, buf->lb_buf, buf->lb_len,
2806                                fs_flags);
2807 }
2808
2809 /*
2810  * Concurrency: @dt is read locked.
2811  */
2812 static int osd_xattr_list(const struct lu_env *env, struct dt_object *dt,
2813                           struct lu_buf *buf, struct lustre_capa *capa)
2814 {
2815         struct osd_object      *obj    = osd_dt_obj(dt);
2816         struct inode           *inode  = obj->oo_inode;
2817         struct osd_thread_info *info   = osd_oti_get(env);
2818         struct dentry          *dentry = &info->oti_obj_dentry;
2819
2820         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2821         LASSERT(inode->i_op != NULL && inode->i_op->listxattr != NULL);
2822         LASSERT(osd_read_locked(env, obj) || osd_write_locked(env, obj));
2823
2824         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_READ))
2825                 return -EACCES;
2826
2827         dentry->d_inode = inode;
2828         dentry->d_sb = inode->i_sb;
2829         return inode->i_op->listxattr(dentry, buf->lb_buf, buf->lb_len);
2830 }
2831
2832 static int osd_declare_xattr_del(const struct lu_env *env,
2833                                  struct dt_object *dt, const char *name,
2834                                  struct thandle *handle)
2835 {
2836         struct osd_thandle *oh;
2837
2838         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2839         LASSERT(handle != NULL);
2840
2841         oh = container_of0(handle, struct osd_thandle, ot_super);
2842         LASSERT(oh->ot_handle == NULL);
2843
2844         osd_trans_declare_op(env, oh, OSD_OT_XATTR_SET,
2845                              osd_dto_credits_noquota[DTO_XATTR_SET]);
2846
2847         return 0;
2848 }
2849
2850 /*
2851  * Concurrency: @dt is write locked.
2852  */
2853 static int osd_xattr_del(const struct lu_env *env, struct dt_object *dt,
2854                          const char *name, struct thandle *handle,
2855                          struct lustre_capa *capa)
2856 {
2857         struct osd_object      *obj    = osd_dt_obj(dt);
2858         struct inode           *inode  = obj->oo_inode;
2859         struct osd_thread_info *info   = osd_oti_get(env);
2860         struct dentry          *dentry = &info->oti_obj_dentry;
2861         int                     rc;
2862
2863         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2864         LASSERT(inode->i_op != NULL && inode->i_op->removexattr != NULL);
2865         LASSERT(handle != NULL);
2866
2867         if (osd_object_auth(env, dt, capa, CAPA_OPC_META_WRITE))
2868                 return -EACCES;
2869
2870         osd_trans_exec_op(env, handle, OSD_OT_XATTR_SET);
2871
2872         ll_vfs_dq_init(inode);
2873         dentry->d_inode = inode;
2874         dentry->d_sb = inode->i_sb;
2875         rc = inode->i_op->removexattr(dentry, name);
2876         return rc;
2877 }
2878
2879 static struct obd_capa *osd_capa_get(const struct lu_env *env,
2880                                      struct dt_object *dt,
2881                                      struct lustre_capa *old,
2882                                      __u64 opc)
2883 {
2884         struct osd_thread_info *info = osd_oti_get(env);
2885         const struct lu_fid *fid = lu_object_fid(&dt->do_lu);
2886         struct osd_object *obj = osd_dt_obj(dt);
2887         struct osd_device *dev = osd_obj2dev(obj);
2888         struct lustre_capa_key *key = &info->oti_capa_key;
2889         struct lustre_capa *capa = &info->oti_capa;
2890         struct obd_capa *oc;
2891         struct md_capainfo *ci;
2892         int rc;
2893         ENTRY;
2894
2895         if (!dev->od_fl_capa)
2896                 RETURN(ERR_PTR(-ENOENT));
2897
2898         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
2899         LINVRNT(osd_invariant(obj));
2900
2901         /* renewal sanity check */
2902         if (old && osd_object_auth(env, dt, old, opc))
2903                 RETURN(ERR_PTR(-EACCES));
2904
2905         ci = md_capainfo(env);
2906         if (unlikely(!ci))
2907                 RETURN(ERR_PTR(-ENOENT));
2908
2909         switch (ci->mc_auth) {
2910         case LC_ID_NONE:
2911                 RETURN(NULL);
2912         case LC_ID_PLAIN:
2913                 capa->lc_uid = obj->oo_inode->i_uid;
2914                 capa->lc_gid = obj->oo_inode->i_gid;
2915                 capa->lc_flags = LC_ID_PLAIN;
2916                 break;
2917         case LC_ID_CONVERT: {
2918                 __u32 d[4], s[4];
2919
2920                 s[0] = obj->oo_inode->i_uid;
2921                 cfs_get_random_bytes(&(s[1]), sizeof(__u32));
2922                 s[2] = obj->oo_inode->i_gid;
2923                 cfs_get_random_bytes(&(s[3]), sizeof(__u32));
2924                 rc = capa_encrypt_id(d, s, key->lk_key, CAPA_HMAC_KEY_MAX_LEN);
2925                 if (unlikely(rc))
2926                         RETURN(ERR_PTR(rc));
2927
2928                 capa->lc_uid   = ((__u64)d[1] << 32) | d[0];
2929                 capa->lc_gid   = ((__u64)d[3] << 32) | d[2];
2930                 capa->lc_flags = LC_ID_CONVERT;
2931                 break;
2932         }
2933         default:
2934                 RETURN(ERR_PTR(-EINVAL));
2935         }
2936
2937         capa->lc_fid = *fid;
2938         capa->lc_opc = opc;
2939         capa->lc_flags |= dev->od_capa_alg << 24;
2940         capa->lc_timeout = dev->od_capa_timeout;
2941         capa->lc_expiry = 0;
2942
2943         oc = capa_lookup(dev->od_capa_hash, capa, 1);
2944         if (oc) {
2945                 LASSERT(!capa_is_expired(oc));
2946                 RETURN(oc);
2947         }
2948
2949         spin_lock(&capa_lock);
2950         *key = dev->od_capa_keys[1];
2951         spin_unlock(&capa_lock);
2952
2953         capa->lc_keyid = key->lk_keyid;
2954         capa->lc_expiry = cfs_time_current_sec() + dev->od_capa_timeout;
2955
2956         rc = capa_hmac(capa->lc_hmac, capa, key->lk_key);
2957         if (rc) {
2958                 DEBUG_CAPA(D_ERROR, capa, "HMAC failed: %d for", rc);
2959                 RETURN(ERR_PTR(rc));
2960         }
2961
2962         oc = capa_add(dev->od_capa_hash, capa);
2963         RETURN(oc);
2964 }
2965
2966 static int osd_object_sync(const struct lu_env *env, struct dt_object *dt)
2967 {
2968         struct osd_object       *obj    = osd_dt_obj(dt);
2969         struct inode            *inode  = obj->oo_inode;
2970         struct osd_thread_info  *info   = osd_oti_get(env);
2971         struct dentry           *dentry = &info->oti_obj_dentry;
2972         struct file             *file   = &info->oti_file;
2973         int                     rc;
2974
2975         ENTRY;
2976
2977         dentry->d_inode = inode;
2978         dentry->d_sb = inode->i_sb;
2979         file->f_dentry = dentry;
2980         file->f_mapping = inode->i_mapping;
2981         file->f_op = inode->i_fop;
2982 #ifndef HAVE_FILE_FSYNC_4ARGS
2983         mutex_lock(&inode->i_mutex);
2984 #endif
2985         rc = do_fsync(file, 0);
2986 #ifndef HAVE_FILE_FSYNC_4ARGS
2987         mutex_unlock(&inode->i_mutex);
2988 #endif
2989         RETURN(rc);
2990 }
2991
2992 static int osd_data_get(const struct lu_env *env, struct dt_object *dt,
2993                         void **data)
2994 {
2995         struct osd_object *obj = osd_dt_obj(dt);
2996         ENTRY;
2997
2998         *data = (void *)obj->oo_inode;
2999         RETURN(0);
3000 }
3001
3002 /*
3003  * Index operations.
3004  */
3005
3006 static int osd_iam_index_probe(const struct lu_env *env, struct osd_object *o,
3007                            const struct dt_index_features *feat)
3008 {
3009         struct iam_descr *descr;
3010
3011         if (osd_object_is_root(o))
3012                 return feat == &dt_directory_features;
3013
3014         LASSERT(o->oo_dir != NULL);
3015
3016         descr = o->oo_dir->od_container.ic_descr;
3017         if (feat == &dt_directory_features) {
3018                 if (descr->id_rec_size == sizeof(struct osd_fid_pack))
3019                         return 1;
3020                 else
3021                         return 0;
3022         } else {
3023                 return
3024                         feat->dif_keysize_min <= descr->id_key_size &&
3025                         descr->id_key_size <= feat->dif_keysize_max &&
3026                         feat->dif_recsize_min <= descr->id_rec_size &&
3027                         descr->id_rec_size <= feat->dif_recsize_max &&
3028                         !(feat->dif_flags & (DT_IND_VARKEY |
3029                                              DT_IND_VARREC | DT_IND_NONUNQ)) &&
3030                         ergo(feat->dif_flags & DT_IND_UPDATE,
3031                              1 /* XXX check that object (and file system) is
3032                                 * writable */);
3033         }
3034 }
3035
3036 static int osd_iam_container_init(const struct lu_env *env,
3037                                   struct osd_object *obj,
3038                                   struct osd_directory *dir)
3039 {
3040         struct iam_container *bag = &dir->od_container;
3041         int result;
3042
3043         result = iam_container_init(bag, &dir->od_descr, obj->oo_inode);
3044         if (result != 0)
3045                 return result;
3046
3047         result = iam_container_setup(bag);
3048         if (result == 0)
3049                 obj->oo_dt.do_index_ops = &osd_index_iam_ops;
3050         else
3051                 iam_container_fini(bag);
3052
3053         return result;
3054 }
3055
3056
3057 /*
3058  * Concurrency: no external locking is necessary.
3059  */
3060 static int osd_index_try(const struct lu_env *env, struct dt_object *dt,
3061                          const struct dt_index_features *feat)
3062 {
3063         int                      result;
3064         int                      skip_iam = 0;
3065         struct osd_object       *obj = osd_dt_obj(dt);
3066
3067         LINVRNT(osd_invariant(obj));
3068
3069         if (osd_object_is_root(obj)) {
3070                 dt->do_index_ops = &osd_index_ea_ops;
3071                 result = 0;
3072         } else if (feat == &dt_directory_features) {
3073                 dt->do_index_ops = &osd_index_ea_ops;
3074                 if (obj->oo_inode != NULL && S_ISDIR(obj->oo_inode->i_mode))
3075                         result = 0;
3076                 else
3077                         result = -ENOTDIR;
3078                 skip_iam = 1;
3079         } else if (unlikely(feat == &dt_otable_features)) {
3080                 dt->do_index_ops = &osd_otable_ops;
3081                 return 0;
3082         } else if (unlikely(feat == &dt_acct_features)) {
3083                 dt->do_index_ops = &osd_acct_index_ops;
3084                 result = 0;
3085                 skip_iam = 1;
3086         } else if (!osd_has_index(obj)) {
3087                 struct osd_directory *dir;
3088
3089                 OBD_ALLOC_PTR(dir);
3090                 if (dir != NULL) {
3091
3092                         spin_lock(&obj->oo_guard);
3093                         if (obj->oo_dir == NULL)
3094                                 obj->oo_dir = dir;
3095                         else
3096                                 /*
3097                                  * Concurrent thread allocated container data.
3098                                  */
3099                                 OBD_FREE_PTR(dir);
3100                         spin_unlock(&obj->oo_guard);
3101                         /*
3102                          * Now, that we have container data, serialize its
3103                          * initialization.
3104                          */
3105                         down_write(&obj->oo_ext_idx_sem);
3106                         /*
3107                          * recheck under lock.
3108                          */
3109                         if (!osd_has_index(obj))
3110                                 result = osd_iam_container_init(env, obj, dir);
3111                         else
3112                                 result = 0;
3113                         up_write(&obj->oo_ext_idx_sem);
3114                 } else {
3115                         result = -ENOMEM;
3116                 }
3117         } else {
3118                 result = 0;
3119         }
3120
3121         if (result == 0 && skip_iam == 0) {
3122                 if (!osd_iam_index_probe(env, obj, feat))
3123                         result = -ENOTDIR;
3124         }
3125         LINVRNT(osd_invariant(obj));
3126
3127         if (result == 0 && is_quota_glb_feat(feat) &&
3128             fid_seq(lu_object_fid(&dt->do_lu)) == FID_SEQ_QUOTA_GLB)
3129                 result = osd_quota_migration(env, dt, feat);
3130
3131         return result;
3132 }
3133
3134 static int osd_otable_it_attr_get(const struct lu_env *env,
3135                                  struct dt_object *dt,
3136                                  struct lu_attr *attr,
3137                                  struct lustre_capa *capa)
3138 {
3139         attr->la_valid = 0;
3140         return 0;
3141 }
3142
3143 static const struct dt_object_operations osd_obj_ops = {
3144         .do_read_lock         = osd_object_read_lock,
3145         .do_write_lock        = osd_object_write_lock,
3146         .do_read_unlock       = osd_object_read_unlock,
3147         .do_write_unlock      = osd_object_write_unlock,
3148         .do_write_locked      = osd_object_write_locked,
3149         .do_attr_get          = osd_attr_get,
3150         .do_declare_attr_set  = osd_declare_attr_set,
3151         .do_attr_set          = osd_attr_set,
3152         .do_ah_init           = osd_ah_init,
3153         .do_declare_create    = osd_declare_object_create,
3154         .do_create            = osd_object_create,
3155         .do_declare_destroy   = osd_declare_object_destroy,
3156         .do_destroy           = osd_object_destroy,
3157         .do_index_try         = osd_index_try,
3158         .do_declare_ref_add   = osd_declare_object_ref_add,
3159         .do_ref_add           = osd_object_ref_add,
3160         .do_declare_ref_del   = osd_declare_object_ref_del,
3161         .do_ref_del           = osd_object_ref_del,
3162         .do_xattr_get         = osd_xattr_get,
3163         .do_declare_xattr_set = osd_declare_xattr_set,
3164         .do_xattr_set         = osd_xattr_set,
3165         .do_declare_xattr_del = osd_declare_xattr_del,
3166         .do_xattr_del         = osd_xattr_del,
3167         .do_xattr_list        = osd_xattr_list,
3168         .do_capa_get          = osd_capa_get,
3169         .do_object_sync       = osd_object_sync,
3170         .do_data_get          = osd_data_get,
3171 };
3172
3173 /**
3174  * dt_object_operations for interoperability mode
3175  * (i.e. to run 2.0 mds on 1.8 disk) (b11826)
3176  */
3177 static const struct dt_object_operations osd_obj_ea_ops = {
3178         .do_read_lock         = osd_object_read_lock,
3179         .do_write_lock        = osd_object_write_lock,
3180         .do_read_unlock       = osd_object_read_unlock,
3181         .do_write_unlock      = osd_object_write_unlock,
3182         .do_write_locked      = osd_object_write_locked,
3183         .do_attr_get          = osd_attr_get,
3184         .do_declare_attr_set  = osd_declare_attr_set,
3185         .do_attr_set          = osd_attr_set,
3186         .do_ah_init           = osd_ah_init,
3187         .do_declare_create    = osd_declare_object_create,
3188         .do_create            = osd_object_ea_create,
3189         .do_declare_destroy   = osd_declare_object_destroy,
3190         .do_destroy           = osd_object_destroy,
3191         .do_index_try         = osd_index_try,
3192         .do_declare_ref_add   = osd_declare_object_ref_add,
3193         .do_ref_add           = osd_object_ref_add,
3194         .do_declare_ref_del   = osd_declare_object_ref_del,
3195         .do_ref_del           = osd_object_ref_del,
3196         .do_xattr_get         = osd_xattr_get,
3197         .do_declare_xattr_set = osd_declare_xattr_set,
3198         .do_xattr_set         = osd_xattr_set,
3199         .do_declare_xattr_del = osd_declare_xattr_del,
3200         .do_xattr_del         = osd_xattr_del,
3201         .do_xattr_list        = osd_xattr_list,
3202         .do_capa_get          = osd_capa_get,
3203         .do_object_sync       = osd_object_sync,
3204         .do_data_get          = osd_data_get,
3205 };
3206
3207 static const struct dt_object_operations osd_obj_otable_it_ops = {
3208         .do_attr_get    = osd_otable_it_attr_get,
3209         .do_index_try   = osd_index_try,
3210 };
3211
3212 static int osd_index_declare_iam_delete(const struct lu_env *env,
3213                                         struct dt_object *dt,
3214                                         const struct dt_key *key,
3215                                         struct thandle *handle)
3216 {
3217         struct osd_thandle    *oh;
3218
3219         oh = container_of0(handle, struct osd_thandle, ot_super);
3220         LASSERT(oh->ot_handle == NULL);
3221
3222         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3223                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3224
3225         return 0;
3226 }
3227
3228 /**
3229  *      delete a (key, value) pair from index \a dt specified by \a key
3230  *
3231  *      \param  dt      osd index object
3232  *      \param  key     key for index
3233  *      \param  rec     record reference
3234  *      \param  handle  transaction handler
3235  *
3236  *      \retval  0  success
3237  *      \retval -ve   failure
3238  */
3239
3240 static int osd_index_iam_delete(const struct lu_env *env, struct dt_object *dt,
3241                                 const struct dt_key *key,
3242                                 struct thandle *handle,
3243                                 struct lustre_capa *capa)
3244 {
3245         struct osd_thread_info *oti = osd_oti_get(env);
3246         struct osd_object      *obj = osd_dt_obj(dt);
3247         struct osd_thandle     *oh;
3248         struct iam_path_descr  *ipd;
3249         struct iam_container   *bag = &obj->oo_dir->od_container;
3250         int                     rc;
3251
3252         ENTRY;
3253
3254         LINVRNT(osd_invariant(obj));
3255         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3256         LASSERT(bag->ic_object == obj->oo_inode);
3257         LASSERT(handle != NULL);
3258
3259         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3260                 RETURN(-EACCES);
3261
3262         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3263
3264         ipd = osd_idx_ipd_get(env, bag);
3265         if (unlikely(ipd == NULL))
3266                 RETURN(-ENOMEM);
3267
3268         oh = container_of0(handle, struct osd_thandle, ot_super);
3269         LASSERT(oh->ot_handle != NULL);
3270         LASSERT(oh->ot_handle->h_transaction != NULL);
3271
3272         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3273                 /* swab quota uid/gid provided by caller */
3274                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3275                 key = (const struct dt_key *)&oti->oti_quota_id;
3276         }
3277
3278         rc = iam_delete(oh->ot_handle, bag, (const struct iam_key *)key, ipd);
3279         osd_ipd_put(env, bag, ipd);
3280         LINVRNT(osd_invariant(obj));
3281         RETURN(rc);
3282 }
3283
3284 static int osd_index_declare_ea_delete(const struct lu_env *env,
3285                                        struct dt_object *dt,
3286                                        const struct dt_key *key,
3287                                        struct thandle *handle)
3288 {
3289         struct osd_thandle *oh;
3290         struct inode       *inode;
3291         int                 rc;
3292         ENTRY;
3293
3294         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3295         LASSERT(handle != NULL);
3296
3297         oh = container_of0(handle, struct osd_thandle, ot_super);
3298         LASSERT(oh->ot_handle == NULL);
3299
3300         osd_trans_declare_op(env, oh, OSD_OT_DELETE,
3301                              osd_dto_credits_noquota[DTO_INDEX_DELETE]);
3302
3303         inode = osd_dt_obj(dt)->oo_inode;
3304         LASSERT(inode);
3305
3306         rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0, oh,
3307                                    true, true, NULL, false);
3308         RETURN(rc);
3309 }
3310
3311 static inline int osd_get_fid_from_dentry(struct ldiskfs_dir_entry_2 *de,
3312                                           struct dt_rec *fid)
3313 {
3314         struct osd_fid_pack *rec;
3315         int                  rc = -ENODATA;
3316
3317         if (de->file_type & LDISKFS_DIRENT_LUFID) {
3318                 rec = (struct osd_fid_pack *) (de->name + de->name_len + 1);
3319                 rc = osd_fid_unpack((struct lu_fid *)fid, rec);
3320         }
3321         return rc;
3322 }
3323
3324 static int osd_remote_fid(const struct lu_env *env, struct osd_device *osd,
3325                           struct lu_fid *fid)
3326 {
3327         struct lu_seq_range     *range = &osd_oti_get(env)->oti_seq_range;
3328         struct seq_server_site  *ss = osd_seq_site(osd);
3329         int                     rc;
3330         ENTRY;
3331
3332         /* Those FID seqs, which are not in FLDB, must be local seq */
3333         if (unlikely(!fid_seq_in_fldb(fid_seq(fid)) || ss == NULL))
3334                 RETURN(0);
3335
3336         rc = osd_fld_lookup(env, osd, fid, range);
3337         if (rc != 0) {
3338                 CERROR("%s: Can not lookup fld for "DFID"\n",
3339                        osd_name(osd), PFID(fid));
3340                 RETURN(rc);
3341         }
3342
3343         RETURN(ss->ss_node_id != range->lsr_index);
3344 }
3345
3346 /**
3347  * Index delete function for interoperability mode (b11826).
3348  * It will remove the directory entry added by osd_index_ea_insert().
3349  * This entry is needed to maintain name->fid mapping.
3350  *
3351  * \param key,  key i.e. file entry to be deleted
3352  *
3353  * \retval   0, on success
3354  * \retval -ve, on error
3355  */
3356 static int osd_index_ea_delete(const struct lu_env *env, struct dt_object *dt,
3357                                const struct dt_key *key,
3358                                struct thandle *handle,
3359                                struct lustre_capa *capa)
3360 {
3361         struct osd_object          *obj    = osd_dt_obj(dt);
3362         struct inode               *dir    = obj->oo_inode;
3363         struct dentry              *dentry;
3364         struct osd_thandle         *oh;
3365         struct ldiskfs_dir_entry_2 *de = NULL;
3366         struct buffer_head         *bh;
3367         struct htree_lock          *hlock = NULL;
3368         struct lu_fid              *fid = &osd_oti_get(env)->oti_fid;
3369         struct osd_device          *osd = osd_dev(dt->do_lu.lo_dev);
3370         int                        rc;
3371         ENTRY;
3372
3373         LINVRNT(osd_invariant(obj));
3374         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3375         LASSERT(handle != NULL);
3376
3377         osd_trans_exec_op(env, handle, OSD_OT_DELETE);
3378
3379         oh = container_of(handle, struct osd_thandle, ot_super);
3380         LASSERT(oh->ot_handle != NULL);
3381         LASSERT(oh->ot_handle->h_transaction != NULL);
3382
3383         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_DELETE))
3384                 RETURN(-EACCES);
3385
3386         ll_vfs_dq_init(dir);
3387         dentry = osd_child_dentry_get(env, obj,
3388                                       (char *)key, strlen((char *)key));
3389
3390         if (obj->oo_hl_head != NULL) {
3391                 hlock = osd_oti_get(env)->oti_hlock;
3392                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3393                                    dir, LDISKFS_HLOCK_DEL);
3394         } else {
3395                 down_write(&obj->oo_ext_idx_sem);
3396         }
3397
3398         bh = ldiskfs_find_entry(dir, &dentry->d_name, &de, hlock);
3399         if (bh) {
3400                 __u32 ino = 0;
3401
3402                 /* If this is not the ".." entry, it might be a remote DNE
3403                  * entry and  we need to check if the FID is for a remote
3404                  * MDT.  If the FID is  not in the directory entry (e.g.
3405                  * upgraded 1.8 filesystem without dirdata enabled) then
3406                  * we need to get the FID from the LMA. For a remote directory
3407                  * there HAS to be an LMA, it cannot be an IGIF inode in this
3408                  * case.
3409                  *
3410                  * Delete the entry before the agent inode in order to
3411                  * simplify error handling.  At worst an error after deleting
3412                  * the entry first might leak the agent inode afterward. The
3413                  * reverse would need filesystem abort in case of error deleting
3414                  * the entry after the agent had been removed, or leave a
3415                  * dangling entry pointing at a random inode. */
3416                 if (strcmp((char *)key, dotdot) != 0) {
3417                         LASSERT(de != NULL);
3418                         rc = osd_get_fid_from_dentry(de, (struct dt_rec *)fid);
3419                         /* If Fid is not in dentry, try to get it from LMA */
3420                         if (rc == -ENODATA) {
3421                                 struct osd_inode_id *id;
3422                                 struct inode *inode;
3423
3424                                 /* Before trying to get fid from the inode,
3425                                  * check whether the inode is valid.
3426                                  *
3427                                  * If the inode has been deleted, do not go
3428                                  * ahead to do osd_ea_fid_get, which will set
3429                                  * the inode to bad inode, which might cause
3430                                  * the inode to be deleted uncorrectly */
3431                                 inode = ldiskfs_iget(osd_sb(osd),
3432                                                      le32_to_cpu(de->inode));
3433                                 if (IS_ERR(inode)) {
3434                                         CDEBUG(D_INODE, "%s: "DFID"get inode"
3435                                                "error.\n", osd_name(osd),
3436                                                PFID(fid));
3437                                         rc = PTR_ERR(inode);
3438                                 } else {
3439                                         if (likely(inode->i_nlink != 0)) {
3440                                                 id = &osd_oti_get(env)->oti_id;
3441                                                 rc = osd_ea_fid_get(env, obj,
3442                                                         le32_to_cpu(de->inode),
3443                                                                     fid, id);
3444                                         } else {
3445                                                 CDEBUG(D_INFO, "%s: %u "DFID
3446                                                        "deleted.\n",
3447                                                        osd_name(osd),
3448                                                        le32_to_cpu(de->inode),
3449                                                        PFID(fid));
3450                                                 rc = -ESTALE;
3451                                         }
3452                                         iput(inode);
3453                                 }
3454                         }
3455                         if (rc == 0 &&
3456                             unlikely(osd_remote_fid(env, osd, fid)))
3457                                 /* Need to delete agent inode */
3458                                 ino = le32_to_cpu(de->inode);
3459                 }
3460                 rc = ldiskfs_delete_entry(oh->ot_handle, dir, de, bh);
3461                 brelse(bh);
3462                 if (rc == 0 && unlikely(ino != 0)) {
3463                         rc = osd_delete_local_agent_inode(env, osd, fid, ino,
3464                                                           oh);
3465                         if (rc != 0)
3466                                 CERROR("%s: del local inode "DFID": rc = %d\n",
3467                                        osd_name(osd), PFID(fid), rc);
3468                 }
3469         } else {
3470                 rc = -ENOENT;
3471         }
3472         if (hlock != NULL)
3473                 ldiskfs_htree_unlock(hlock);
3474         else
3475                 up_write(&obj->oo_ext_idx_sem);
3476
3477         if (rc != 0)
3478                 GOTO(out, rc);
3479
3480         /* For inode on the remote MDT, .. will point to
3481          * /Agent directory, Check whether it needs to delete
3482          * from agent directory */
3483         if (unlikely(strcmp((char *)key, dotdot) == 0)) {
3484                 rc = osd_delete_from_remote_parent(env, osd_obj2dev(obj), obj,
3485                                                    oh);
3486                 if (rc != 0 && rc != -ENOENT) {
3487                         CERROR("%s: delete agent inode "DFID": rc = %d\n",
3488                                osd_name(osd), PFID(fid), rc);
3489                 }
3490
3491                 if (rc == -ENOENT)
3492                         rc = 0;
3493
3494                 GOTO(out, rc);
3495         }
3496 out:
3497
3498         LASSERT(osd_invariant(obj));
3499         RETURN(rc);
3500 }
3501
3502 /**
3503  *      Lookup index for \a key and copy record to \a rec.
3504  *
3505  *      \param  dt      osd index object
3506  *      \param  key     key for index
3507  *      \param  rec     record reference
3508  *
3509  *      \retval  +ve  success : exact mach
3510  *      \retval  0    return record with key not greater than \a key
3511  *      \retval -ve   failure
3512  */
3513 static int osd_index_iam_lookup(const struct lu_env *env, struct dt_object *dt,
3514                                 struct dt_rec *rec, const struct dt_key *key,
3515                                 struct lustre_capa *capa)
3516 {
3517         struct osd_object      *obj = osd_dt_obj(dt);
3518         struct iam_path_descr  *ipd;
3519         struct iam_container   *bag = &obj->oo_dir->od_container;
3520         struct osd_thread_info *oti = osd_oti_get(env);
3521         struct iam_iterator    *it = &oti->oti_idx_it;
3522         struct iam_rec         *iam_rec;
3523         int                     rc;
3524
3525         ENTRY;
3526
3527         LASSERT(osd_invariant(obj));
3528         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3529         LASSERT(bag->ic_object == obj->oo_inode);
3530
3531         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
3532                 RETURN(-EACCES);
3533
3534         ipd = osd_idx_ipd_get(env, bag);
3535         if (IS_ERR(ipd))
3536                 RETURN(-ENOMEM);
3537
3538         /* got ipd now we can start iterator. */
3539         iam_it_init(it, bag, 0, ipd);
3540
3541         if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3542                 /* swab quota uid/gid provided by caller */
3543                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3544                 key = (const struct dt_key *)&oti->oti_quota_id;
3545         }
3546
3547         rc = iam_it_get(it, (struct iam_key *)key);
3548         if (rc >= 0) {
3549                 if (S_ISDIR(obj->oo_inode->i_mode))
3550                         iam_rec = (struct iam_rec *)oti->oti_ldp;
3551                 else
3552                         iam_rec = (struct iam_rec *) rec;
3553
3554                 iam_reccpy(&it->ii_path.ip_leaf, (struct iam_rec *)iam_rec);
3555
3556                 if (S_ISDIR(obj->oo_inode->i_mode))
3557                         osd_fid_unpack((struct lu_fid *) rec,
3558                                        (struct osd_fid_pack *)iam_rec);
3559                 else if (fid_is_quota(lu_object_fid(&dt->do_lu)))
3560                         osd_quota_unpack(obj, rec);
3561         }
3562
3563         iam_it_put(it);
3564         iam_it_fini(it);
3565         osd_ipd_put(env, bag, ipd);
3566
3567         LINVRNT(osd_invariant(obj));
3568
3569         RETURN(rc);
3570 }
3571
3572 static int osd_index_declare_iam_insert(const struct lu_env *env,
3573                                         struct dt_object *dt,
3574                                         const struct dt_rec *rec,
3575                                         const struct dt_key *key,
3576                                         struct thandle *handle)
3577 {
3578         struct osd_thandle *oh;
3579
3580         LASSERT(handle != NULL);
3581
3582         oh = container_of0(handle, struct osd_thandle, ot_super);
3583         LASSERT(oh->ot_handle == NULL);
3584
3585         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
3586                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
3587
3588         return 0;
3589 }
3590
3591 /**
3592  *      Inserts (key, value) pair in \a dt index object.
3593  *
3594  *      \param  dt      osd index object
3595  *      \param  key     key for index
3596  *      \param  rec     record reference
3597  *      \param  th      transaction handler
3598  *
3599  *      \retval  0  success
3600  *      \retval -ve failure
3601  */
3602 static int osd_index_iam_insert(const struct lu_env *env, struct dt_object *dt,
3603                                 const struct dt_rec *rec,
3604                                 const struct dt_key *key, struct thandle *th,
3605                                 struct lustre_capa *capa, int ignore_quota)
3606 {
3607         struct osd_object     *obj = osd_dt_obj(dt);
3608         struct iam_path_descr *ipd;
3609         struct osd_thandle    *oh;
3610         struct iam_container  *bag = &obj->oo_dir->od_container;
3611         struct osd_thread_info *oti = osd_oti_get(env);
3612         struct iam_rec         *iam_rec;
3613         int                     rc;
3614
3615         ENTRY;
3616
3617         LINVRNT(osd_invariant(obj));
3618         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
3619         LASSERT(bag->ic_object == obj->oo_inode);
3620         LASSERT(th != NULL);
3621
3622         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
3623                 RETURN(-EACCES);
3624
3625         osd_trans_exec_op(env, th, OSD_OT_INSERT);
3626
3627         ipd = osd_idx_ipd_get(env, bag);
3628         if (unlikely(ipd == NULL))
3629                 RETURN(-ENOMEM);
3630
3631         oh = container_of0(th, struct osd_thandle, ot_super);
3632         LASSERT(oh->ot_handle != NULL);
3633         LASSERT(oh->ot_handle->h_transaction != NULL);
3634         if (S_ISDIR(obj->oo_inode->i_mode)) {
3635                 iam_rec = (struct iam_rec *)oti->oti_ldp;
3636                 osd_fid_pack((struct osd_fid_pack *)iam_rec, rec, &oti->oti_fid);
3637         } else if (fid_is_quota(lu_object_fid(&dt->do_lu))) {
3638                 /* pack quota uid/gid */
3639                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
3640                 key = (const struct dt_key *)&oti->oti_quota_id;
3641                 /* pack quota record */
3642                 rec = osd_quota_pack(obj, rec, &oti->oti_quota_rec);
3643                 iam_rec = (struct iam_rec *)rec;
3644         } else {
3645                 iam_rec = (struct iam_rec *)rec;
3646         }
3647
3648         rc = iam_insert(oh->ot_handle, bag, (const struct iam_key *)key,
3649                         iam_rec, ipd);
3650         osd_ipd_put(env, bag, ipd);
3651         LINVRNT(osd_invariant(obj));
3652         RETURN(rc);
3653 }
3654
3655 /**
3656  * Calls ldiskfs_add_entry() to add directory entry
3657  * into the directory. This is required for
3658  * interoperability mode (b11826)
3659  *
3660  * \retval   0, on success
3661  * \retval -ve, on error
3662  */
3663 static int __osd_ea_add_rec(struct osd_thread_info *info,
3664                             struct osd_object *pobj, struct inode  *cinode,
3665                             const char *name, const struct dt_rec *fid,
3666                             struct htree_lock *hlock, struct thandle *th)
3667 {
3668         struct ldiskfs_dentry_param *ldp;
3669         struct dentry               *child;
3670         struct osd_thandle          *oth;
3671         int                          rc;
3672
3673         oth = container_of(th, struct osd_thandle, ot_super);
3674         LASSERT(oth->ot_handle != NULL);
3675         LASSERT(oth->ot_handle->h_transaction != NULL);
3676         LASSERT(pobj->oo_inode);
3677
3678         ldp = (struct ldiskfs_dentry_param *)info->oti_ldp;
3679         if (unlikely(pobj->oo_inode ==
3680                      osd_sb(osd_obj2dev(pobj))->s_root->d_inode))
3681                 ldp->edp_magic = 0;
3682         else
3683                 osd_get_ldiskfs_dirent_param(ldp, fid);
3684         child = osd_child_dentry_get(info->oti_env, pobj, name, strlen(name));
3685         child->d_fsdata = (void *)ldp;
3686         ll_vfs_dq_init(pobj->oo_inode);
3687         rc = osd_ldiskfs_add_entry(oth->ot_handle, child, cinode, hlock);
3688
3689         RETURN(rc);
3690 }
3691
3692 /**
3693  * Calls ldiskfs_add_dot_dotdot() to add dot and dotdot entries
3694  * into the directory.Also sets flags into osd object to
3695  * indicate dot and dotdot are created. This is required for
3696  * interoperability mode (b11826)
3697  *
3698  * \param dir   directory for dot and dotdot fixup.
3699  * \param obj   child object for linking
3700  *
3701  * \retval   0, on success
3702  * \retval -ve, on error
3703  */
3704 static int osd_add_dot_dotdot(struct osd_thread_info *info,
3705                               struct osd_object *dir,
3706                               struct inode  *parent_dir, const char *name,
3707                               const struct dt_rec *dot_fid,
3708                               const struct dt_rec *dot_dot_fid,
3709                               struct thandle *th)
3710 {
3711         struct inode                *inode = dir->oo_inode;
3712         struct osd_thandle          *oth;
3713         int result = 0;
3714
3715         oth = container_of(th, struct osd_thandle, ot_super);
3716         LASSERT(oth->ot_handle->h_transaction != NULL);
3717         LASSERT(S_ISDIR(dir->oo_inode->i_mode));
3718
3719         if (strcmp(name, dot) == 0) {
3720                 if (dir->oo_compat_dot_created) {
3721                         result = -EEXIST;
3722                 } else {
3723                         LASSERT(inode == parent_dir);
3724                         dir->oo_compat_dot_created = 1;
3725                         result = 0;
3726                 }
3727         } else if (strcmp(name, dotdot) == 0) {
3728                 if (!dir->oo_compat_dot_created)
3729                         return -EINVAL;
3730                 /* in case of rename, dotdot is already created */
3731                 if (dir->oo_compat_dotdot_created) {
3732                         return __osd_ea_add_rec(info, dir, parent_dir, name,
3733                                                 dot_dot_fid, NULL, th);
3734                 }
3735
3736                 result = osd_add_dot_dotdot_internal(info, dir->oo_inode,
3737                                                 parent_dir, dot_fid,
3738                                                 dot_dot_fid, oth);
3739                 if (result == 0)
3740                         dir->oo_compat_dotdot_created = 1;
3741         }
3742
3743         return result;
3744 }
3745
3746
3747 /**
3748  * It will call the appropriate osd_add* function and return the
3749  * value, return by respective functions.
3750  */
3751 static int osd_ea_add_rec(const struct lu_env *env, struct osd_object *pobj,
3752                           struct inode *cinode, const char *name,
3753                           const struct dt_rec *fid, struct thandle *th)
3754 {
3755         struct osd_thread_info *info   = osd_oti_get(env);
3756         struct htree_lock      *hlock;
3757         int                     rc;
3758
3759         hlock = pobj->oo_hl_head != NULL ? info->oti_hlock : NULL;
3760
3761         if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' &&
3762                                                    name[2] =='\0'))) {
3763                 if (hlock != NULL) {
3764                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3765                                            pobj->oo_inode, 0);
3766                 } else {
3767                         down_write(&pobj->oo_ext_idx_sem);
3768                 }
3769                 rc = osd_add_dot_dotdot(info, pobj, cinode, name,
3770                      (struct dt_rec *)lu_object_fid(&pobj->oo_dt.do_lu),
3771                                         fid, th);
3772         } else {
3773                 if (hlock != NULL) {
3774                         ldiskfs_htree_lock(hlock, pobj->oo_hl_head,
3775                                            pobj->oo_inode, LDISKFS_HLOCK_ADD);
3776                 } else {
3777                         down_write(&pobj->oo_ext_idx_sem);
3778                 }
3779
3780                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_INDIR)) {
3781                         struct lu_fid *tfid = &info->oti_fid;
3782
3783                         *tfid = *(const struct lu_fid *)fid;
3784                         tfid->f_ver = ~0;
3785                         rc = __osd_ea_add_rec(info, pobj, cinode, name,
3786                                               (const struct dt_rec *)tfid,
3787                                               hlock, th);
3788                 } else {
3789                         rc = __osd_ea_add_rec(info, pobj, cinode, name, fid,
3790                                               hlock, th);
3791                 }
3792         }
3793         if (hlock != NULL)
3794                 ldiskfs_htree_unlock(hlock);
3795         else
3796                 up_write(&pobj->oo_ext_idx_sem);
3797
3798         return rc;
3799 }
3800
3801 static void
3802 osd_consistency_check(struct osd_thread_info *oti, struct osd_device *dev,
3803                       struct osd_idmap_cache *oic)
3804 {
3805         struct osd_scrub    *scrub = &dev->od_scrub;
3806         struct lu_fid       *fid   = &oic->oic_fid;
3807         struct osd_inode_id *id    = &oti->oti_id;
3808         int                  once  = 0;
3809         int                  rc;
3810         ENTRY;
3811
3812         if (!fid_is_norm(fid) && !fid_is_igif(fid))
3813                 RETURN_EXIT;
3814
3815 again:
3816         rc = osd_oi_lookup(oti, dev, fid, id, OI_CHECK_FLD);
3817         if (rc != 0 && rc != -ENOENT)
3818                 RETURN_EXIT;
3819
3820         if (rc == 0 && osd_id_eq(id, &oic->oic_lid))
3821                 RETURN_EXIT;
3822
3823         if (thread_is_running(&scrub->os_thread)) {
3824                 rc = osd_oii_insert(dev, oic, rc == -ENOENT);
3825                 /* There is race condition between osd_oi_lookup and OI scrub.
3826                  * The OI scrub finished just after osd_oi_lookup() failure.
3827                  * Under such case, it is unnecessary to trigger OI scrub again,
3828                  * but try to call osd_oi_lookup() again. */
3829                 if (unlikely(rc == -EAGAIN))
3830                         goto again;
3831
3832                 RETURN_EXIT;
3833         }
3834
3835         if (!dev->od_noscrub && ++once == 1) {
3836                 CDEBUG(D_LFSCK, "Trigger OI scrub by RPC for "DFID"\n",
3837                        PFID(fid));
3838                 rc = osd_scrub_start(dev);
3839                 LCONSOLE_ERROR("%.16s: trigger OI scrub by RPC for "DFID
3840                                ", rc = %d [2]\n",
3841                                LDISKFS_SB(osd_sb(dev))->s_es->s_volume_name,
3842                                PFID(fid), rc);
3843                 if (rc == 0)
3844                         goto again;
3845         }
3846
3847         EXIT;
3848 }
3849
3850 static int osd_fail_fid_lookup(struct osd_thread_info *oti,
3851                                struct osd_device *dev,
3852                                struct osd_idmap_cache *oic,
3853                                struct lu_fid *fid, __u32 ino)
3854 {
3855         struct lustre_mdt_attrs *lma   = &oti->oti_mdt_attrs;
3856         struct inode            *inode;
3857         int                      rc;
3858
3859         osd_id_gen(&oic->oic_lid, ino, OSD_OII_NOGEN);
3860         inode = osd_iget(oti, dev, &oic->oic_lid);
3861         if (IS_ERR(inode)) {
3862                 fid_zero(&oic->oic_fid);
3863                 return PTR_ERR(inode);
3864         }
3865
3866         rc = osd_get_lma(oti, inode, &oti->oti_obj_dentry, lma);
3867         iput(inode);
3868         if (rc != 0)
3869                 fid_zero(&oic->oic_fid);
3870         else
3871                 *fid = oic->oic_fid = lma->lma_self_fid;
3872         return rc;
3873 }
3874
3875 int osd_add_oi_cache(struct osd_thread_info *info, struct osd_device *osd,
3876                      struct osd_inode_id *id, const struct lu_fid *fid)
3877 {
3878         CDEBUG(D_INODE, "add "DFID" %u:%u to info %p\n", PFID(fid),
3879                id->oii_ino, id->oii_gen, info);
3880         info->oti_cache.oic_lid = *id;
3881         info->oti_cache.oic_fid = *fid;
3882
3883         return 0;
3884 }
3885
3886 /**
3887  * Calls ->lookup() to find dentry. From dentry get inode and
3888  * read inode's ea to get fid. This is required for  interoperability
3889  * mode (b11826)
3890  *
3891  * \retval   0, on success
3892  * \retval -ve, on error
3893  */
3894 static int osd_ea_lookup_rec(const struct lu_env *env, struct osd_object *obj,
3895                              struct dt_rec *rec, const struct dt_key *key)
3896 {
3897         struct inode               *dir    = obj->oo_inode;
3898         struct dentry              *dentry;
3899         struct ldiskfs_dir_entry_2 *de;
3900         struct buffer_head         *bh;
3901         struct lu_fid              *fid = (struct lu_fid *) rec;
3902         struct htree_lock          *hlock = NULL;
3903         int                         ino;
3904         int                         rc;
3905         ENTRY;
3906
3907         LASSERT(dir->i_op != NULL && dir->i_op->lookup != NULL);
3908
3909         dentry = osd_child_dentry_get(env, obj,
3910                                       (char *)key, strlen((char *)key));
3911
3912         if (obj->oo_hl_head != NULL) {
3913                 hlock = osd_oti_get(env)->oti_hlock;
3914                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
3915                                    dir, LDISKFS_HLOCK_LOOKUP);
3916         } else {
3917                 down_read(&obj->oo_ext_idx_sem);
3918         }
3919
3920         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
3921         if (bh) {
3922                 struct osd_thread_info *oti = osd_oti_get(env);
3923                 struct osd_inode_id *id = &oti->oti_id;
3924                 struct osd_idmap_cache *oic = &oti->oti_cache;
3925                 struct osd_device *dev = osd_obj2dev(obj);
3926                 struct osd_scrub *scrub = &dev->od_scrub;
3927                 struct scrub_file *sf = &scrub->os_file;
3928
3929                 ino = le32_to_cpu(de->inode);
3930                 if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP)) {
3931                         brelse(bh);
3932                         rc = osd_fail_fid_lookup(oti, dev, oic, fid, ino);
3933                         GOTO(out, rc);
3934                 }
3935
3936                 rc = osd_get_fid_from_dentry(de, rec);
3937
3938                 /* done with de, release bh */
3939                 brelse(bh);
3940                 if (rc != 0)
3941                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
3942                 else
3943                         osd_id_gen(id, ino, OSD_OII_NOGEN);
3944                 if (rc != 0 || osd_remote_fid(env, dev, fid)) {
3945                         fid_zero(&oic->oic_fid);
3946                         GOTO(out, rc);
3947                 }
3948
3949                 rc = osd_add_oi_cache(osd_oti_get(env), osd_obj2dev(obj), id,
3950                                       fid);
3951                 if (rc != 0)
3952                         GOTO(out, rc);
3953                 if ((scrub->os_pos_current <= ino) &&
3954                     ((sf->sf_flags & SF_INCONSISTENT) ||
3955                      (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
3956                      ldiskfs_test_bit(osd_oi_fid2idx(dev, fid),
3957                                       sf->sf_oi_bitmap)))
3958                         osd_consistency_check(oti, dev, oic);
3959         } else {
3960                 rc = -ENOENT;
3961         }
3962
3963         GOTO(out, rc);
3964
3965 out:
3966         if (hlock != NULL)
3967                 ldiskfs_htree_unlock(hlock);
3968         else
3969                 up_read(&obj->oo_ext_idx_sem);
3970         return rc;
3971 }
3972
3973 /**
3974  * Find the osd object for given fid.
3975  *
3976  * \param fid need to find the osd object having this fid
3977  *
3978  * \retval osd_object on success
3979  * \retval        -ve on error
3980  */
3981 struct osd_object *osd_object_find(const struct lu_env *env,
3982                                    struct dt_object *dt,
3983                                    const struct lu_fid *fid)
3984 {
3985         struct lu_device  *ludev = dt->do_lu.lo_dev;
3986         struct osd_object *child = NULL;
3987         struct lu_object  *luch;
3988         struct lu_object  *lo;
3989
3990         /*
3991          * at this point topdev might not exist yet
3992          * (i.e. MGS is preparing profiles). so we can
3993          * not rely on topdev and instead lookup with
3994          * our device passed as topdev. this can't work
3995          * if the object isn't cached yet (as osd doesn't
3996          * allocate lu_header). IOW, the object must be
3997          * in the cache, otherwise lu_object_alloc() crashes
3998          * -bzzz
3999          */
4000         luch = lu_object_find_at(env, ludev, fid, NULL);
4001         if (!IS_ERR(luch)) {
4002                 if (lu_object_exists(luch)) {
4003                         lo = lu_object_locate(luch->lo_header, ludev->ld_type);
4004                         if (lo != NULL)
4005                                 child = osd_obj(lo);
4006                         else
4007                                 LU_OBJECT_DEBUG(D_ERROR, env, luch,
4008                                                 "lu_object can't be located"
4009                                                 DFID"\n", PFID(fid));
4010
4011                         if (child == NULL) {
4012                                 lu_object_put(env, luch);
4013                                 CERROR("Unable to get osd_object\n");
4014                                 child = ERR_PTR(-ENOENT);
4015                         }
4016                 } else {
4017                         LU_OBJECT_DEBUG(D_ERROR, env, luch,
4018                                         "lu_object does not exists "DFID"\n",
4019                                         PFID(fid));
4020                         lu_object_put(env, luch);
4021                         child = ERR_PTR(-ENOENT);
4022                 }
4023         } else
4024                 child = (void *)luch;
4025
4026         return child;
4027 }
4028
4029 /**
4030  * Put the osd object once done with it.
4031  *
4032  * \param obj osd object that needs to be put
4033  */
4034 static inline void osd_object_put(const struct lu_env *env,
4035                                   struct osd_object *obj)
4036 {
4037         lu_object_put(env, &obj->oo_dt.do_lu);
4038 }
4039
4040 static int osd_index_declare_ea_insert(const struct lu_env *env,
4041                                        struct dt_object *dt,
4042                                        const struct dt_rec *rec,
4043                                        const struct dt_key *key,
4044                                        struct thandle *handle)
4045 {
4046         struct osd_thandle      *oh;
4047         struct osd_device       *osd   = osd_dev(dt->do_lu.lo_dev);
4048         struct lu_fid           *fid = (struct lu_fid *)rec;
4049         int                     rc;
4050         ENTRY;
4051
4052         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4053         LASSERT(handle != NULL);
4054
4055         oh = container_of0(handle, struct osd_thandle, ot_super);
4056         LASSERT(oh->ot_handle == NULL);
4057
4058         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4059                              osd_dto_credits_noquota[DTO_INDEX_INSERT]);
4060
4061         if (osd_dt_obj(dt)->oo_inode == NULL) {
4062                 const char *name  = (const char *)key;
4063                 /* Object is not being created yet. Only happens when
4064                  *     1. declare directory create
4065                  *     2. declare insert .
4066                  *     3. declare insert ..
4067                  */
4068                 LASSERT(strcmp(name, dotdot) == 0 || strcmp(name, dot) == 0);
4069         } else {
4070                 struct inode *inode = osd_dt_obj(dt)->oo_inode;
4071
4072                 /* We ignore block quota on meta pool (MDTs), so needn't
4073                  * calculate how many blocks will be consumed by this index
4074                  * insert */
4075                 rc = osd_declare_inode_qid(env, inode->i_uid, inode->i_gid, 0,
4076                                            oh, true, true, NULL, false);
4077         }
4078
4079         if (fid == NULL)
4080                 RETURN(0);
4081
4082         rc = osd_remote_fid(env, osd, fid);
4083         if (rc <= 0)
4084                 RETURN(rc);
4085
4086         rc = 0;
4087
4088         osd_trans_declare_op(env, oh, OSD_OT_CREATE,
4089                              osd_dto_credits_noquota[DTO_OBJECT_CREATE]);
4090         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4091                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4092         osd_trans_declare_op(env, oh, OSD_OT_INSERT,
4093                              osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1);
4094
4095         RETURN(rc);
4096 }
4097
4098 /**
4099  * Index add function for interoperability mode (b11826).
4100  * It will add the directory entry.This entry is needed to
4101  * maintain name->fid mapping.
4102  *
4103  * \param key it is key i.e. file entry to be inserted
4104  * \param rec it is value of given key i.e. fid
4105  *
4106  * \retval   0, on success
4107  * \retval -ve, on error
4108  */
4109 static int osd_index_ea_insert(const struct lu_env *env, struct dt_object *dt,
4110                                const struct dt_rec *rec,
4111                                const struct dt_key *key, struct thandle *th,
4112                                struct lustre_capa *capa, int ignore_quota)
4113 {
4114         struct osd_object       *obj = osd_dt_obj(dt);
4115         struct osd_device       *osd = osd_dev(dt->do_lu.lo_dev);
4116         struct lu_fid           *fid = (struct lu_fid *) rec;
4117         const char              *name = (const char *)key;
4118         struct osd_thread_info  *oti   = osd_oti_get(env);
4119         struct osd_inode_id     *id    = &oti->oti_id;
4120         struct inode            *child_inode = NULL;
4121         struct osd_object       *child = NULL;
4122         int                     rc;
4123         ENTRY;
4124
4125         LASSERT(osd_invariant(obj));
4126         LASSERT(dt_object_exists(dt) && !dt_object_remote(dt));
4127         LASSERT(th != NULL);
4128
4129         osd_trans_exec_op(env, th, OSD_OT_INSERT);
4130
4131         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_INSERT))
4132                 RETURN(-EACCES);
4133
4134         LASSERTF(fid_is_sane(fid), "fid"DFID" is insane!", PFID(fid));
4135
4136         rc = osd_remote_fid(env, osd, fid);
4137         if (rc < 0) {
4138                 CERROR("%s: Can not find object "DFID" rc %d\n",
4139                        osd_name(osd), PFID(fid), rc);
4140                 RETURN(rc);
4141         }
4142
4143         if (rc == 1) {
4144                 /* Insert remote entry */
4145                 if (strcmp(name, dotdot) == 0 && strlen(name) == 2) {
4146                         struct osd_mdobj_map    *omm = osd->od_mdt_map;
4147                         struct osd_thandle      *oh;
4148
4149                         /* If parent on remote MDT, we need put this object
4150                          * under AGENT */
4151                         oh = container_of(th, typeof(*oh), ot_super);
4152                         rc = osd_add_to_remote_parent(env, osd, obj, oh);
4153                         if (rc != 0) {
4154                                 CERROR("%s: add "DFID" error: rc = %d\n",
4155                                        osd_name(osd),
4156                                        PFID(lu_object_fid(&dt->do_lu)), rc);
4157                                 RETURN(rc);
4158                         }
4159
4160                         child_inode = igrab(omm->omm_remote_parent->d_inode);
4161                 } else {
4162                         child_inode = osd_create_local_agent_inode(env, osd,
4163                                                                    obj, fid,
4164                                                                    th);
4165                         if (IS_ERR(child_inode))
4166                                 RETURN(PTR_ERR(child_inode));
4167                 }
4168         } else {
4169                 /* Insert local entry */
4170                 child = osd_object_find(env, dt, fid);
4171                 if (IS_ERR(child)) {
4172                         CERROR("%s: Can not find object "DFID"%u:%u: rc = %d\n",
4173                                osd_name(osd), PFID(fid),
4174                                id->oii_ino, id->oii_gen,
4175                                (int)PTR_ERR(child_inode));
4176                         RETURN(PTR_ERR(child_inode));
4177                 }
4178                 child_inode = igrab(child->oo_inode);
4179         }
4180
4181         rc = osd_ea_add_rec(env, obj, child_inode, name, rec, th);
4182
4183         iput(child_inode);
4184         if (child != NULL)
4185                 osd_object_put(env, child);
4186         LASSERT(osd_invariant(obj));
4187         RETURN(rc);
4188 }
4189
4190 /**
4191  *  Initialize osd Iterator for given osd index object.
4192  *
4193  *  \param  dt      osd index object
4194  */
4195
4196 static struct dt_it *osd_it_iam_init(const struct lu_env *env,
4197                                      struct dt_object *dt,
4198                                      __u32 unused,
4199                                      struct lustre_capa *capa)
4200 {
4201         struct osd_it_iam      *it;
4202         struct osd_thread_info *oti = osd_oti_get(env);
4203         struct osd_object      *obj = osd_dt_obj(dt);
4204         struct lu_object       *lo  = &dt->do_lu;
4205         struct iam_path_descr  *ipd;
4206         struct iam_container   *bag = &obj->oo_dir->od_container;
4207
4208         LASSERT(lu_object_exists(lo));
4209
4210         if (osd_object_auth(env, dt, capa, CAPA_OPC_BODY_READ))
4211                 return ERR_PTR(-EACCES);
4212
4213         it = &oti->oti_it;
4214         ipd = osd_it_ipd_get(env, bag);
4215         if (likely(ipd != NULL)) {
4216                 it->oi_obj = obj;
4217                 it->oi_ipd = ipd;
4218                 lu_object_get(lo);
4219                 iam_it_init(&it->oi_it, bag, IAM_IT_MOVE, ipd);
4220                 return (struct dt_it *)it;
4221         }
4222         return ERR_PTR(-ENOMEM);
4223 }
4224
4225 /**
4226  * free given Iterator.
4227  */
4228
4229 static void osd_it_iam_fini(const struct lu_env *env, struct dt_it *di)
4230 {
4231         struct osd_it_iam *it = (struct osd_it_iam *)di;
4232         struct osd_object *obj = it->oi_obj;
4233
4234         iam_it_fini(&it->oi_it);
4235         osd_ipd_put(env, &obj->oo_dir->od_container, it->oi_ipd);
4236         lu_object_put(env, &obj->oo_dt.do_lu);
4237 }
4238
4239 /**
4240  *  Move Iterator to record specified by \a key
4241  *
4242  *  \param  di      osd iterator
4243  *  \param  key     key for index
4244  *
4245  *  \retval +ve  di points to record with least key not larger than key
4246  *  \retval  0   di points to exact matched key
4247  *  \retval -ve  failure
4248  */
4249
4250 static int osd_it_iam_get(const struct lu_env *env,
4251                           struct dt_it *di, const struct dt_key *key)
4252 {
4253         struct osd_thread_info  *oti = osd_oti_get(env);
4254         struct osd_it_iam       *it = (struct osd_it_iam *)di;
4255
4256         if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4257                 /* swab quota uid/gid */
4258                 oti->oti_quota_id = cpu_to_le64(*((__u64 *)key));
4259                 key = (struct dt_key *)&oti->oti_quota_id;
4260         }
4261
4262         return iam_it_get(&it->oi_it, (const struct iam_key *)key);
4263 }
4264
4265 /**
4266  *  Release Iterator
4267  *
4268  *  \param  di      osd iterator
4269  */
4270 static void osd_it_iam_put(const struct lu_env *env, struct dt_it *di)
4271 {
4272         struct osd_it_iam *it = (struct osd_it_iam *)di;
4273
4274         iam_it_put(&it->oi_it);
4275 }
4276
4277 /**
4278  *  Move iterator by one record
4279  *
4280  *  \param  di      osd iterator
4281  *
4282  *  \retval +1   end of container reached
4283  *  \retval  0   success
4284  *  \retval -ve  failure
4285  */
4286
4287 static int osd_it_iam_next(const struct lu_env *env, struct dt_it *di)
4288 {
4289         struct osd_it_iam *it = (struct osd_it_iam *)di;
4290
4291         return iam_it_next(&it->oi_it);
4292 }
4293
4294 /**
4295  * Return pointer to the key under iterator.
4296  */
4297
4298 static struct dt_key *osd_it_iam_key(const struct lu_env *env,
4299                                  const struct dt_it *di)
4300 {
4301         struct osd_thread_info *oti = osd_oti_get(env);
4302         struct osd_it_iam      *it = (struct osd_it_iam *)di;
4303         struct osd_object      *obj = it->oi_obj;
4304         struct dt_key          *key;
4305
4306         key = (struct dt_key *)iam_it_key_get(&it->oi_it);
4307
4308         if (!IS_ERR(key) && fid_is_quota(lu_object_fid(&obj->oo_dt.do_lu))) {
4309                 /* swab quota uid/gid */
4310                 oti->oti_quota_id = le64_to_cpu(*((__u64 *)key));
4311                 key = (struct dt_key *)&oti->oti_quota_id;
4312         }
4313
4314         return key;
4315 }
4316
4317 /**
4318  * Return size of key under iterator (in bytes)
4319  */
4320
4321 static int osd_it_iam_key_size(const struct lu_env *env, const struct dt_it *di)
4322 {
4323         struct osd_it_iam *it = (struct osd_it_iam *)di;
4324
4325         return iam_it_key_size(&it->oi_it);
4326 }
4327
4328 static inline void
4329 osd_it_append_attrs(struct lu_dirent *ent, int len, __u16 type)
4330 {
4331         /* check if file type is required */
4332         if (ent->lde_attrs & LUDA_TYPE) {
4333                 struct luda_type *lt;
4334                 int align = sizeof(*lt) - 1;
4335
4336                 len = (len + align) & ~align;
4337                 lt = (struct luda_type *)(ent->lde_name + len);
4338                 lt->lt_type = cpu_to_le16(DTTOIF(type));
4339         }
4340
4341         ent->lde_attrs = cpu_to_le32(ent->lde_attrs);
4342 }
4343
4344 /**
4345  * build lu direct from backend fs dirent.
4346  */
4347
4348 static inline void
4349 osd_it_pack_dirent(struct lu_dirent *ent, struct lu_fid *fid, __u64 offset,
4350                    char *name, __u16 namelen, __u16 type, __u32 attr)
4351 {
4352         ent->lde_attrs = attr | LUDA_FID;
4353         fid_cpu_to_le(&ent->lde_fid, fid);
4354
4355         ent->lde_hash = cpu_to_le64(offset);
4356         ent->lde_reclen = cpu_to_le16(lu_dirent_calc_size(namelen, attr));
4357
4358         strncpy(ent->lde_name, name, namelen);
4359         ent->lde_name[namelen] = '\0';
4360         ent->lde_namelen = cpu_to_le16(namelen);
4361
4362         /* append lustre attributes */
4363         osd_it_append_attrs(ent, namelen, type);
4364 }
4365
4366 /**
4367  * Return pointer to the record under iterator.
4368  */
4369 static int osd_it_iam_rec(const struct lu_env *env,
4370                           const struct dt_it *di,
4371                           struct dt_rec *dtrec, __u32 attr)
4372 {
4373         struct osd_it_iam      *it   = (struct osd_it_iam *)di;
4374         struct osd_thread_info *info = osd_oti_get(env);
4375         ENTRY;
4376
4377         if (S_ISDIR(it->oi_obj->oo_inode->i_mode)) {
4378                 const struct osd_fid_pack *rec;
4379                 struct lu_fid             *fid = &info->oti_fid;
4380                 struct lu_dirent          *lde = (struct lu_dirent *)dtrec;
4381                 char                      *name;
4382                 int                        namelen;
4383                 __u64                      hash;
4384                 int                        rc;
4385
4386                 name = (char *)iam_it_key_get(&it->oi_it);
4387                 if (IS_ERR(name))
4388                         RETURN(PTR_ERR(name));
4389
4390                 namelen = iam_it_key_size(&it->oi_it);
4391
4392                 rec = (const struct osd_fid_pack *)iam_it_rec_get(&it->oi_it);
4393                 if (IS_ERR(rec))
4394                         RETURN(PTR_ERR(rec));
4395
4396                 rc = osd_fid_unpack(fid, rec);
4397                 if (rc)
4398                         RETURN(rc);
4399
4400                 hash = iam_it_store(&it->oi_it);
4401
4402                 /* IAM does not store object type in IAM index (dir) */
4403                 osd_it_pack_dirent(lde, fid, hash, name, namelen,
4404                                    0, LUDA_FID);
4405         } else if (fid_is_quota(lu_object_fid(&it->oi_obj->oo_dt.do_lu))) {
4406                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4407                            (struct iam_rec *)dtrec);
4408                 osd_quota_unpack(it->oi_obj, dtrec);
4409         } else {
4410                 iam_reccpy(&it->oi_it.ii_path.ip_leaf,
4411                            (struct iam_rec *)dtrec);
4412         }
4413
4414         RETURN(0);
4415 }
4416
4417 /**
4418  * Returns cookie for current Iterator position.
4419  */
4420 static __u64 osd_it_iam_store(const struct lu_env *env, const struct dt_it *di)
4421 {
4422         struct osd_it_iam *it = (struct osd_it_iam *)di;
4423
4424         return iam_it_store(&it->oi_it);
4425 }
4426
4427 /**
4428  * Restore iterator from cookie.
4429  *
4430  * \param  di      osd iterator
4431  * \param  hash    Iterator location cookie
4432  *
4433  * \retval +ve  di points to record with least key not larger than key.
4434  * \retval  0   di points to exact matched key
4435  * \retval -ve  failure
4436  */
4437
4438 static int osd_it_iam_load(const struct lu_env *env,
4439                            const struct dt_it *di, __u64 hash)
4440 {
4441         struct osd_it_iam *it = (struct osd_it_iam *)di;
4442
4443         return iam_it_load(&it->oi_it, hash);
4444 }
4445
4446 static const struct dt_index_operations osd_index_iam_ops = {
4447         .dio_lookup         = osd_index_iam_lookup,
4448         .dio_declare_insert = osd_index_declare_iam_insert,
4449         .dio_insert         = osd_index_iam_insert,
4450         .dio_declare_delete = osd_index_declare_iam_delete,
4451         .dio_delete         = osd_index_iam_delete,
4452         .dio_it     = {
4453                 .init     = osd_it_iam_init,
4454                 .fini     = osd_it_iam_fini,
4455                 .get      = osd_it_iam_get,
4456                 .put      = osd_it_iam_put,
4457                 .next     = osd_it_iam_next,
4458                 .key      = osd_it_iam_key,
4459                 .key_size = osd_it_iam_key_size,
4460                 .rec      = osd_it_iam_rec,
4461                 .store    = osd_it_iam_store,
4462                 .load     = osd_it_iam_load
4463         }
4464 };
4465
4466
4467 /**
4468  * Creates or initializes iterator context.
4469  *
4470  * \retval struct osd_it_ea, iterator structure on success
4471  *
4472  */
4473 static struct dt_it *osd_it_ea_init(const struct lu_env *env,
4474                                     struct dt_object *dt,
4475                                     __u32 attr,
4476                                     struct lustre_capa *capa)
4477 {
4478         struct osd_object       *obj  = osd_dt_obj(dt);
4479         struct osd_thread_info  *info = osd_oti_get(env);
4480         struct osd_it_ea        *it   = &info->oti_it_ea;
4481         struct file             *file = &it->oie_file;
4482         struct lu_object        *lo   = &dt->do_lu;
4483         struct dentry           *obj_dentry = &info->oti_it_dentry;
4484         ENTRY;
4485         LASSERT(lu_object_exists(lo));
4486
4487         obj_dentry->d_inode = obj->oo_inode;
4488         obj_dentry->d_sb = osd_sb(osd_obj2dev(obj));
4489         obj_dentry->d_name.hash = 0;
4490
4491         it->oie_rd_dirent       = 0;
4492         it->oie_it_dirent       = 0;
4493         it->oie_dirent          = NULL;
4494         it->oie_buf             = info->oti_it_ea_buf;
4495         it->oie_obj             = obj;
4496
4497         /* Reset the "file" totally to avoid to reuse any old value from
4498          * former readdir handling, the "file->f_pos" should be zero. */
4499         memset(file, 0, sizeof(*file));
4500         /* Only FMODE_64BITHASH or FMODE_32BITHASH should be set, NOT both. */
4501         if (attr & LUDA_64BITHASH)
4502                 file->f_mode    = FMODE_64BITHASH;
4503         else
4504                 file->f_mode    = FMODE_32BITHASH;
4505         file->f_dentry          = obj_dentry;
4506         file->f_mapping         = obj->oo_inode->i_mapping;
4507         file->f_op              = obj->oo_inode->i_fop;
4508         lu_object_get(lo);
4509         RETURN((struct dt_it *) it);
4510 }
4511
4512 /**
4513  * Destroy or finishes iterator context.
4514  *
4515  * \param di iterator structure to be destroyed
4516  */
4517 static void osd_it_ea_fini(const struct lu_env *env, struct dt_it *di)
4518 {
4519         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4520         struct osd_object    *obj  = it->oie_obj;
4521         struct inode       *inode  = obj->oo_inode;
4522
4523         ENTRY;
4524         it->oie_file.f_op->release(inode, &it->oie_file);
4525         lu_object_put(env, &obj->oo_dt.do_lu);
4526         EXIT;
4527 }
4528
4529 /**
4530  * It position the iterator at given key, so that next lookup continues from
4531  * that key Or it is similar to dio_it->load() but based on a key,
4532  * rather than file position.
4533  *
4534  * As a special convention, osd_it_ea_get(env, di, "") has to rewind iterator
4535  * to the beginning.
4536  *
4537  * TODO: Presently return +1 considering it is only used by mdd_dir_is_empty().
4538  */
4539 static int osd_it_ea_get(const struct lu_env *env,
4540                          struct dt_it *di, const struct dt_key *key)
4541 {
4542         struct osd_it_ea     *it   = (struct osd_it_ea *)di;
4543
4544         ENTRY;
4545         LASSERT(((const char *)key)[0] == '\0');
4546         it->oie_file.f_pos      = 0;
4547         it->oie_rd_dirent       = 0;
4548         it->oie_it_dirent       = 0;
4549         it->oie_dirent          = NULL;
4550
4551         RETURN(+1);
4552 }
4553
4554 /**
4555  * Does nothing
4556  */
4557 static void osd_it_ea_put(const struct lu_env *env, struct dt_it *di)
4558 {
4559 }
4560
4561 /**
4562  * It is called internally by ->readdir(). It fills the
4563  * iterator's in-memory data structure with required
4564  * information i.e. name, namelen, rec_size etc.
4565  *
4566  * \param buf in which information to be filled in.
4567  * \param name name of the file in given dir
4568  *
4569  * \retval 0 on success
4570  * \retval 1 on buffer full
4571  */
4572 static int osd_ldiskfs_filldir(char *buf, const char *name, int namelen,
4573                                loff_t offset, __u64 ino,
4574                                unsigned d_type)
4575 {
4576         struct osd_it_ea        *it   = (struct osd_it_ea *)buf;
4577         struct osd_object       *obj  = it->oie_obj;
4578         struct osd_it_ea_dirent *ent  = it->oie_dirent;
4579         struct lu_fid           *fid  = &ent->oied_fid;
4580         struct osd_fid_pack     *rec;
4581         ENTRY;
4582
4583         /* this should never happen */
4584         if (unlikely(namelen == 0 || namelen > LDISKFS_NAME_LEN)) {
4585                 CERROR("ldiskfs return invalid namelen %d\n", namelen);
4586                 RETURN(-EIO);
4587         }
4588
4589         if ((void *) ent - it->oie_buf + sizeof(*ent) + namelen >
4590             OSD_IT_EA_BUFSIZE)
4591                 RETURN(1);
4592
4593         /* "." is just the object itself. */
4594         if (namelen == 1 && name[0] == '.') {
4595                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4596         } else if (d_type & LDISKFS_DIRENT_LUFID) {
4597                 rec = (struct osd_fid_pack*) (name + namelen + 1);
4598                 if (osd_fid_unpack(fid, rec) != 0)
4599                         fid_zero(fid);
4600         } else {
4601                 fid_zero(fid);
4602         }
4603         d_type &= ~LDISKFS_DIRENT_LUFID;
4604
4605         /* NOT export local root. */
4606         if (unlikely(osd_sb(osd_obj2dev(obj))->s_root->d_inode->i_ino == ino)) {
4607                 ino = obj->oo_inode->i_ino;
4608                 *fid = obj->oo_dt.do_lu.lo_header->loh_fid;
4609         }
4610
4611         ent->oied_ino     = ino;
4612         ent->oied_off     = offset;
4613         ent->oied_namelen = namelen;
4614         ent->oied_type    = d_type;
4615
4616         memcpy(ent->oied_name, name, namelen);
4617
4618         it->oie_rd_dirent++;
4619         it->oie_dirent = (void *) ent + cfs_size_round(sizeof(*ent) + namelen);
4620         RETURN(0);
4621 }
4622
4623 /**
4624  * Calls ->readdir() to load a directory entry at a time
4625  * and stored it in iterator's in-memory data structure.
4626  *
4627  * \param di iterator's in memory structure
4628  *
4629  * \retval   0 on success
4630  * \retval -ve on error
4631  */
4632 static int osd_ldiskfs_it_fill(const struct lu_env *env,
4633                                const struct dt_it *di)
4634 {
4635         struct osd_it_ea   *it    = (struct osd_it_ea *)di;
4636         struct osd_object  *obj   = it->oie_obj;
4637         struct inode       *inode = obj->oo_inode;
4638         struct htree_lock  *hlock = NULL;
4639         int                 result = 0;
4640
4641         ENTRY;
4642         it->oie_dirent = it->oie_buf;
4643         it->oie_rd_dirent = 0;
4644
4645         if (obj->oo_hl_head != NULL) {
4646                 hlock = osd_oti_get(env)->oti_hlock;
4647                 ldiskfs_htree_lock(hlock, obj->oo_hl_head,
4648                                    inode, LDISKFS_HLOCK_READDIR);
4649         } else {
4650                 down_read(&obj->oo_ext_idx_sem);
4651         }
4652
4653         result = inode->i_fop->readdir(&it->oie_file, it,
4654                                        (filldir_t) osd_ldiskfs_filldir);
4655
4656         if (hlock != NULL)
4657                 ldiskfs_htree_unlock(hlock);
4658         else
4659                 up_read(&obj->oo_ext_idx_sem);
4660
4661         if (it->oie_rd_dirent == 0) {
4662                 result = -EIO;
4663         } else {
4664                 it->oie_dirent = it->oie_buf;
4665                 it->oie_it_dirent = 1;
4666         }
4667
4668         RETURN(result);
4669 }
4670
4671 /**
4672  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
4673  * to load a directory entry at a time and stored it in
4674  * iterator's in-memory data structure.
4675  *
4676  * \param di iterator's in memory structure
4677  *
4678  * \retval +ve iterator reached to end
4679  * \retval   0 iterator not reached to end
4680  * \retval -ve on error
4681  */
4682 static int osd_it_ea_next(const struct lu_env *env, struct dt_it *di)
4683 {
4684         struct osd_it_ea *it = (struct osd_it_ea *)di;
4685         int rc;
4686
4687         ENTRY;
4688
4689         if (it->oie_it_dirent < it->oie_rd_dirent) {
4690                 it->oie_dirent =
4691                         (void *) it->oie_dirent +
4692                         cfs_size_round(sizeof(struct osd_it_ea_dirent) +
4693                                        it->oie_dirent->oied_namelen);
4694                 it->oie_it_dirent++;
4695                 RETURN(0);
4696         } else {
4697                 if (it->oie_file.f_pos == ldiskfs_get_htree_eof(&it->oie_file))
4698                         rc = +1;
4699                 else
4700                         rc = osd_ldiskfs_it_fill(env, di);
4701         }
4702
4703         RETURN(rc);
4704 }
4705
4706 /**
4707  * Returns the key at current position from iterator's in memory structure.
4708  *
4709  * \param di iterator's in memory structure
4710  *
4711  * \retval key i.e. struct dt_key on success
4712  */
4713 static struct dt_key *osd_it_ea_key(const struct lu_env *env,
4714                                     const struct dt_it *di)
4715 {
4716         struct osd_it_ea *it = (struct osd_it_ea *)di;
4717
4718         return (struct dt_key *)it->oie_dirent->oied_name;
4719 }
4720
4721 /**
4722  * Returns the key's size at current position from iterator's in memory structure.
4723  *
4724  * \param di iterator's in memory structure
4725  *
4726  * \retval key_size i.e. struct dt_key on success
4727  */
4728 static int osd_it_ea_key_size(const struct lu_env *env, const struct dt_it *di)
4729 {
4730         struct osd_it_ea *it = (struct osd_it_ea *)di;
4731
4732         return it->oie_dirent->oied_namelen;
4733 }
4734
4735 static int
4736 osd_dirent_update(handle_t *jh, struct super_block *sb,
4737                   struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4738                   struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de)
4739 {
4740         struct osd_fid_pack *rec;
4741         int                  rc;
4742         ENTRY;
4743
4744         LASSERT(de->file_type & LDISKFS_DIRENT_LUFID);
4745         LASSERT(de->rec_len >= de->name_len + sizeof(struct osd_fid_pack));
4746
4747         rc = ldiskfs_journal_get_write_access(jh, bh);
4748         if (rc != 0) {
4749                 CERROR("%.16s: fail to write access for update dirent: "
4750                        "name = %.*s, rc = %d\n",
4751                        LDISKFS_SB(sb)->s_es->s_volume_name,
4752                        ent->oied_namelen, ent->oied_name, rc);
4753                 RETURN(rc);
4754         }
4755
4756         rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4757         fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4758         rc = ldiskfs_journal_dirty_metadata(jh, bh);
4759         if (rc != 0)
4760                 CERROR("%.16s: fail to dirty metadata for update dirent: "
4761                        "name = %.*s, rc = %d\n",
4762                        LDISKFS_SB(sb)->s_es->s_volume_name,
4763                        ent->oied_namelen, ent->oied_name, rc);
4764
4765         RETURN(rc);
4766 }
4767
4768 static inline int
4769 osd_dirent_has_space(__u16 reclen, __u16 namelen, unsigned blocksize)
4770 {
4771         if (ldiskfs_rec_len_from_disk(reclen, blocksize) >=
4772             __LDISKFS_DIR_REC_LEN(namelen + 1 + sizeof(struct osd_fid_pack)))
4773                 return 1;
4774         else
4775                 return 0;
4776 }
4777
4778 static inline int
4779 osd_dot_dotdot_has_space(struct ldiskfs_dir_entry_2 *de, int dot_dotdot)
4780 {
4781         LASSERTF(dot_dotdot == 1 || dot_dotdot == 2,
4782                  "dot_dotdot = %d\n", dot_dotdot);
4783
4784         if (LDISKFS_DIR_REC_LEN(de) >=
4785             __LDISKFS_DIR_REC_LEN(dot_dotdot + 1 + sizeof(struct osd_fid_pack)))
4786                 return 1;
4787         else
4788                 return 0;
4789 }
4790
4791 static int
4792 osd_dirent_reinsert(const struct lu_env *env, handle_t *jh,
4793                     struct inode *dir, struct inode *inode,
4794                     struct osd_it_ea_dirent *ent, struct lu_fid *fid,
4795                     struct buffer_head *bh, struct ldiskfs_dir_entry_2 *de,
4796                     struct htree_lock *hlock)
4797 {
4798         struct dentry               *dentry;
4799         struct osd_fid_pack         *rec;
4800         struct ldiskfs_dentry_param *ldp;
4801         int                          rc;
4802         ENTRY;
4803
4804         if (!LDISKFS_HAS_INCOMPAT_FEATURE(inode->i_sb,
4805                                           LDISKFS_FEATURE_INCOMPAT_DIRDATA))
4806                 RETURN(0);
4807
4808         /* There is enough space to hold the FID-in-dirent. */
4809         if (osd_dirent_has_space(de->rec_len, ent->oied_namelen,
4810                                  dir->i_sb->s_blocksize)) {
4811                 rc = ldiskfs_journal_get_write_access(jh, bh);
4812                 if (rc != 0) {
4813                         CERROR("%.16s: fail to write access for reinsert "
4814                                "dirent: name = %.*s, rc = %d\n",
4815                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4816                                ent->oied_namelen, ent->oied_name, rc);
4817                         RETURN(rc);
4818                 }
4819
4820                 de->name[de->name_len] = 0;
4821                 rec = (struct osd_fid_pack *)(de->name + de->name_len + 1);
4822                 rec->fp_len = sizeof(struct lu_fid) + 1;
4823                 fid_cpu_to_be((struct lu_fid *)rec->fp_area, fid);
4824                 de->file_type |= LDISKFS_DIRENT_LUFID;
4825
4826                 rc = ldiskfs_journal_dirty_metadata(jh, bh);
4827                 if (rc != 0)
4828                         CERROR("%.16s: fail to dirty metadata for reinsert "
4829                                "dirent: name = %.*s, rc = %d\n",
4830                                LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4831                                ent->oied_namelen, ent->oied_name, rc);
4832
4833                 RETURN(rc);
4834         }
4835
4836         rc = ldiskfs_delete_entry(jh, dir, de, bh);
4837         if (rc != 0) {
4838                 CERROR("%.16s: fail to delete entry for reinsert dirent: "
4839                        "name = %.*s, rc = %d\n",
4840                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4841                        ent->oied_namelen, ent->oied_name, rc);
4842                 RETURN(rc);
4843         }
4844
4845         dentry = osd_child_dentry_by_inode(env, dir, ent->oied_name,
4846                                            ent->oied_namelen);
4847         ldp = (struct ldiskfs_dentry_param *)osd_oti_get(env)->oti_ldp;
4848         osd_get_ldiskfs_dirent_param(ldp, (const struct dt_rec *)fid);
4849         dentry->d_fsdata = (void *)ldp;
4850         ll_vfs_dq_init(dir);
4851         rc = osd_ldiskfs_add_entry(jh, dentry, inode, hlock);
4852         /* It is too bad, we cannot reinsert the name entry back.
4853          * That means we lose it! */
4854         if (rc != 0)
4855                 CERROR("%.16s: fail to insert entry for reinsert dirent: "
4856                        "name = %.*s, rc = %d\n",
4857                        LDISKFS_SB(inode->i_sb)->s_es->s_volume_name,
4858                        ent->oied_namelen, ent->oied_name, rc);
4859
4860         RETURN(rc);
4861 }
4862
4863 static int
4864 osd_dirent_check_repair(const struct lu_env *env, struct osd_object *obj,
4865                         struct osd_it_ea *it, struct lu_fid *fid,
4866                         struct osd_inode_id *id, __u32 *attr)
4867 {
4868         struct osd_thread_info     *info        = osd_oti_get(env);
4869         struct lustre_mdt_attrs    *lma         = &info->oti_mdt_attrs;
4870         struct osd_device          *dev         = osd_obj2dev(obj);
4871         struct super_block         *sb          = osd_sb(dev);
4872         const char                 *devname     =
4873                                         LDISKFS_SB(sb)->s_es->s_volume_name;
4874         struct osd_it_ea_dirent    *ent         = it->oie_dirent;
4875         struct inode               *dir         = obj->oo_inode;
4876         struct htree_lock          *hlock       = NULL;
4877         struct buffer_head         *bh          = NULL;
4878         handle_t                   *jh          = NULL;
4879         struct ldiskfs_dir_entry_2 *de;
4880         struct dentry              *dentry;
4881         struct inode               *inode;
4882         int                         credits;
4883         int                         rc;
4884         int                         dot_dotdot  = 0;
4885         bool                        dirty       = false;
4886         ENTRY;
4887
4888         if (ent->oied_name[0] == '.') {
4889                 if (ent->oied_namelen == 1)
4890                         dot_dotdot = 1;
4891                 else if (ent->oied_namelen == 2 && ent->oied_name[1] == '.')
4892                         dot_dotdot = 2;
4893         }
4894
4895         dentry = osd_child_dentry_get(env, obj, ent->oied_name,
4896                                       ent->oied_namelen);
4897
4898         /* We need to ensure that the name entry is still valid.
4899          * Because it may be removed or renamed by other already.
4900          *
4901          * The unlink or rename operation will start journal before PDO lock,
4902          * so to avoid deadlock, here we need to start journal handle before
4903          * related PDO lock also. But because we do not know whether there
4904          * will be something to be repaired before PDO lock, we just start
4905          * journal without conditions.
4906          *
4907          * We may need to remove the name entry firstly, then insert back.
4908          * One credit is for user quota file update.
4909          * One credit is for group quota file update.
4910          * Two credits are for dirty inode. */
4911         credits = osd_dto_credits_noquota[DTO_INDEX_DELETE] +
4912                   osd_dto_credits_noquota[DTO_INDEX_INSERT] + 1 + 1 + 2;
4913
4914 again:
4915         if (dev->od_dirent_journal) {
4916                 jh = ldiskfs_journal_start_sb(sb, credits);
4917                 if (IS_ERR(jh)) {
4918                         rc = PTR_ERR(jh);
4919                         CERROR("%.16s: fail to start trans for dirent "
4920                                "check_repair: credits %d, name %.*s, rc %d\n",
4921                                devname, credits, ent->oied_namelen,
4922                                ent->oied_name, rc);
4923                         RETURN(rc);
4924                 }
4925
4926                 if (obj->oo_hl_head != NULL) {
4927                         hlock = osd_oti_get(env)->oti_hlock;
4928                         /* "0" means exclusive lock for the whole directory.
4929                          * We need to prevent others access such name entry
4930                          * during the delete + insert. Neither HLOCK_ADD nor
4931                          * HLOCK_DEL cannot guarantee the atomicity. */
4932                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir, 0);
4933                 } else {
4934                         down_write(&obj->oo_ext_idx_sem);
4935                 }
4936         } else {
4937                 if (obj->oo_hl_head != NULL) {
4938                         hlock = osd_oti_get(env)->oti_hlock;
4939                         ldiskfs_htree_lock(hlock, obj->oo_hl_head, dir,
4940                                            LDISKFS_HLOCK_LOOKUP);
4941                 } else {
4942                         down_read(&obj->oo_ext_idx_sem);
4943                 }
4944         }
4945
4946         bh = osd_ldiskfs_find_entry(dir, dentry, &de, hlock);
4947         /* For dot/dotdot entry, if there is not enough space to hold the
4948          * FID-in-dirent, just keep them there. It only happens when the
4949          * device upgraded from 1.8 or restored from MDT file-level backup.
4950          * For the whole directory, only dot/dotdot entry have no FID-in-dirent
4951          * and needs to get FID from LMA when readdir, it will not affect the
4952          * performance much. */
4953         if ((bh == NULL) || (le32_to_cpu(de->inode) != ent->oied_ino) ||
4954             (dot_dotdot != 0 && !osd_dot_dotdot_has_space(de, dot_dotdot))) {
4955                 *attr |= LUDA_IGNORE;
4956                 GOTO(out_journal, rc = 0);
4957         }
4958
4959         osd_id_gen(id, ent->oied_ino, OSD_OII_NOGEN);
4960         inode = osd_iget(info, dev, id);
4961         if (IS_ERR(inode)) {
4962                 rc = PTR_ERR(inode);
4963                 if (rc == -ENOENT || rc == -ESTALE) {
4964                         *attr |= LUDA_IGNORE;
4965                         rc = 0;
4966                 }
4967
4968                 GOTO(out_journal, rc);
4969         }
4970
4971         /* skip the REMOTE_PARENT_DIR. */
4972         if (inode == dev->od_mdt_map->omm_remote_parent->d_inode)
4973                 GOTO(out_inode, rc = 0);
4974
4975         rc = osd_get_lma(info, inode, &info->oti_obj_dentry, lma);
4976         if (rc == 0) {
4977                 LASSERT(!(lma->lma_compat & LMAC_NOT_IN_OI));
4978
4979                 if (fid_is_sane(fid)) {
4980                         /* FID-in-dirent is valid. */
4981                         if (lu_fid_eq(fid, &lma->lma_self_fid))
4982                                 GOTO(out_inode, rc = 0);
4983
4984                         /* Do not repair under dryrun mode. */
4985                         if (*attr & LUDA_VERIFY_DRYRUN) {
4986                                 *attr |= LUDA_REPAIR;
4987                                 GOTO(out_inode, rc = 0);
4988                         }
4989
4990                         if (!dev->od_dirent_journal) {
4991                                 iput(inode);
4992                                 brelse(bh);
4993                                 if (hlock != NULL)
4994                                         ldiskfs_htree_unlock(hlock);
4995                                 else
4996                                         up_read(&obj->oo_ext_idx_sem);
4997                                 dev->od_dirent_journal = 1;
4998                                 goto again;
4999                         }
5000
5001                         *fid = lma->lma_self_fid;
5002                         dirty = true;
5003                         /* Update the FID-in-dirent. */
5004                         rc = osd_dirent_update(jh, sb, ent, fid, bh, de);
5005                         if (rc == 0)
5006                                 *attr |= LUDA_REPAIR;
5007                 } else {
5008                         /* Do not repair under dryrun mode. */
5009                         if (*attr & LUDA_VERIFY_DRYRUN) {
5010                                 *fid = lma->lma_self_fid;
5011                                 *attr |= LUDA_REPAIR;
5012                                 GOTO(out_inode, rc = 0);
5013                         }
5014
5015                         if (!dev->od_dirent_journal) {
5016                                 iput(inode);
5017                                 brelse(bh);
5018                                 if (hlock != NULL)
5019                                         ldiskfs_htree_unlock(hlock);
5020                                 else
5021                                         up_read(&obj->oo_ext_idx_sem);
5022                                 dev->od_dirent_journal = 1;
5023                                 goto again;
5024                         }
5025
5026                         *fid = lma->lma_self_fid;
5027                         dirty = true;
5028                         /* Append the FID-in-dirent. */
5029                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5030                                                  fid, bh, de, hlock);
5031                         if (rc == 0)
5032                                 *attr |= LUDA_REPAIR;
5033                 }
5034         } else if (rc == -ENODATA) {
5035                 /* Do not repair under dryrun mode. */
5036                 if (*attr & LUDA_VERIFY_DRYRUN) {
5037                         if (fid_is_sane(fid)) {
5038                                 *attr |= LUDA_REPAIR;
5039                         } else {
5040                                 lu_igif_build(fid, inode->i_ino,
5041                                               inode->i_generation);
5042                                 *attr |= LUDA_UPGRADE;
5043                         }
5044                         GOTO(out_inode, rc = 0);
5045                 }
5046
5047                 if (!dev->od_dirent_journal) {
5048                         iput(inode);
5049                         brelse(bh);
5050                         if (hlock != NULL)
5051                                 ldiskfs_htree_unlock(hlock);
5052                         else
5053                                 up_read(&obj->oo_ext_idx_sem);
5054                         dev->od_dirent_journal = 1;
5055                         goto again;
5056                 }
5057
5058                 dirty = true;
5059                 if (unlikely(fid_is_sane(fid))) {
5060                         /* FID-in-dirent exists, but FID-in-LMA is lost.
5061                          * Trust the FID-in-dirent, and add FID-in-LMA. */
5062                         rc = osd_ea_fid_set(info, inode, fid, 0, 0);
5063                         if (rc == 0)
5064                                 *attr |= LUDA_REPAIR;
5065                 } else {
5066                         lu_igif_build(fid, inode->i_ino, inode->i_generation);
5067                         /* It is probably IGIF object. Only aappend the
5068                          * FID-in-dirent. OI scrub will process FID-in-LMA. */
5069                         rc = osd_dirent_reinsert(env, jh, dir, inode, ent,
5070                                                  fid, bh, de, hlock);
5071                         if (rc == 0)
5072                                 *attr |= LUDA_UPGRADE;
5073                 }
5074         }
5075
5076         GOTO(out_inode, rc);
5077
5078 out_inode:
5079         iput(inode);
5080
5081 out_journal:
5082         brelse(bh);
5083         if (hlock != NULL) {
5084                 ldiskfs_htree_unlock(hlock);
5085         } else {
5086                 if (dev->od_dirent_journal)
5087                         up_write(&obj->oo_ext_idx_sem);
5088                 else
5089                         up_read(&obj->oo_ext_idx_sem);
5090         }
5091         if (jh != NULL)
5092                 ldiskfs_journal_stop(jh);
5093         if (rc >= 0 && !dirty)
5094                 dev->od_dirent_journal = 0;
5095         return rc;
5096 }
5097
5098 /**
5099  * Returns the value at current position from iterator's in memory structure.
5100  *
5101  * \param di struct osd_it_ea, iterator's in memory structure
5102  * \param attr attr requested for dirent.
5103  * \param lde lustre dirent
5104  *
5105  * \retval   0 no error and \param lde has correct lustre dirent.
5106  * \retval -ve on error
5107  */
5108 static inline int osd_it_ea_rec(const struct lu_env *env,
5109                                 const struct dt_it *di,
5110                                 struct dt_rec *dtrec, __u32 attr)
5111 {
5112         struct osd_it_ea       *it    = (struct osd_it_ea *)di;
5113         struct osd_object      *obj   = it->oie_obj;
5114         struct osd_device      *dev   = osd_obj2dev(obj);
5115         struct osd_scrub       *scrub = &dev->od_scrub;
5116         struct scrub_file      *sf    = &scrub->os_file;
5117         struct osd_thread_info *oti   = osd_oti_get(env);
5118         struct osd_inode_id    *id    = &oti->oti_id;
5119         struct osd_idmap_cache *oic   = &oti->oti_cache;
5120         struct lu_fid          *fid   = &it->oie_dirent->oied_fid;
5121         struct lu_dirent       *lde   = (struct lu_dirent *)dtrec;
5122         __u32                   ino   = it->oie_dirent->oied_ino;
5123         int                     rc    = 0;
5124         ENTRY;
5125
5126         if (attr & LUDA_VERIFY) {
5127                 attr |= LUDA_TYPE;
5128                 if (unlikely(ino == osd_sb(dev)->s_root->d_inode->i_ino)) {
5129                         attr |= LUDA_IGNORE;
5130                         rc = 0;
5131                 } else {
5132                         rc = osd_dirent_check_repair(env, obj, it, fid, id,
5133                                                      &attr);
5134                 }
5135         } else {
5136                 attr &= ~LU_DIRENT_ATTRS_MASK;
5137                 if (!fid_is_sane(fid)) {
5138                         if (OBD_FAIL_CHECK(OBD_FAIL_FID_LOOKUP))
5139                                 RETURN(-ENOENT);
5140
5141                         rc = osd_ea_fid_get(env, obj, ino, fid, id);
5142                 } else {
5143                         osd_id_gen(id, ino, OSD_OII_NOGEN);
5144                 }
5145         }
5146
5147         /* Pack the entry anyway, at least the offset is right. */
5148         osd_it_pack_dirent(lde, fid, it->oie_dirent->oied_off,
5149                            it->oie_dirent->oied_name,
5150                            it->oie_dirent->oied_namelen,
5151                            it->oie_dirent->oied_type, attr);
5152
5153         if (rc < 0)
5154                 RETURN(rc);
5155
5156         if (osd_remote_fid(env, dev, fid))
5157                 RETURN(0);
5158
5159         if (likely(!(attr & LUDA_IGNORE)))
5160                 rc = osd_add_oi_cache(oti, dev, id, fid);
5161
5162         if (!(attr & LUDA_VERIFY) &&
5163             (scrub->os_pos_current <= ino) &&
5164             ((sf->sf_flags & SF_INCONSISTENT) ||
5165              (sf->sf_flags & SF_UPGRADE && fid_is_igif(fid)) ||
5166              ldiskfs_test_bit(osd_oi_fid2idx(dev, fid), sf->sf_oi_bitmap)))
5167                 osd_consistency_check(oti, dev, oic);
5168
5169         RETURN(rc);
5170 }
5171
5172 /**
5173  * Returns a cookie for current position of the iterator head, so that
5174  * user can use this cookie to load/start the iterator next time.
5175  *
5176  * \param di iterator's in memory structure
5177  *
5178  * \retval cookie for current position, on success
5179  */
5180 static __u64 osd_it_ea_store(const struct lu_env *env, const struct dt_it *di)
5181 {
5182         struct osd_it_ea *it = (struct osd_it_ea *)di;
5183
5184         return it->oie_dirent->oied_off;
5185 }
5186
5187 /**
5188  * It calls osd_ldiskfs_it_fill() which will use ->readdir()
5189  * to load a directory entry at a time and stored it i inn,
5190  * in iterator's in-memory data structure.
5191  *
5192  * \param di struct osd_it_ea, iterator's in memory structure
5193  *
5194  * \retval +ve on success
5195  * \retval -ve on error
5196  */
5197 static int osd_it_ea_load(const struct lu_env *env,
5198                           const struct dt_it *di, __u64 hash)
5199 {
5200         struct osd_it_ea *it = (struct osd_it_ea *)di;
5201         int rc;
5202
5203         ENTRY;
5204         it->oie_file.f_pos = hash;
5205
5206         rc =  osd_ldiskfs_it_fill(env, di);
5207         if (rc == 0)
5208                 rc = +1;
5209
5210         RETURN(rc);
5211 }
5212
5213 /**
5214  * Index lookup function for interoperability mode (b11826).
5215  *
5216  * \param key,  key i.e. file name to be searched
5217  *
5218  * \retval +ve, on success
5219  * \retval -ve, on error
5220  */
5221 static int osd_index_ea_lookup(const struct lu_env *env, struct dt_object *dt,
5222                                struct dt_rec *rec, const struct dt_key *key,
5223                                struct lustre_capa *capa)
5224 {
5225         struct osd_object *obj = osd_dt_obj(dt);
5226         int rc = 0;
5227
5228         ENTRY;
5229
5230         LASSERT(S_ISDIR(obj->oo_inode->i_mode));
5231         LINVRNT(osd_invariant(obj));
5232
5233         if (osd_object_auth(env, dt, capa, CAPA_OPC_INDEX_LOOKUP))
5234                 return -EACCES;
5235
5236         rc = osd_ea_lookup_rec(env, obj, rec, key);
5237         if (rc == 0)
5238                 rc = +1;
5239         RETURN(rc);
5240 }
5241
5242 /**
5243  * Index and Iterator operations for interoperability
5244  * mode (i.e. to run 2.0 mds on 1.8 disk) (b11826)
5245  */
5246 static const struct dt_index_operations osd_index_ea_ops = {
5247         .dio_lookup         = osd_index_ea_lookup,
5248         .dio_declare_insert = osd_index_declare_ea_insert,
5249         .dio_insert         = osd_index_ea_insert,
5250         .dio_declare_delete = osd_index_declare_ea_delete,
5251         .dio_delete         = osd_index_ea_delete,
5252         .dio_it     = {
5253                 .init     = osd_it_ea_init,
5254                 .fini     = osd_it_ea_fini,
5255                 .get      = osd_it_ea_get,
5256                 .put      = osd_it_ea_put,
5257                 .next     = osd_it_ea_next,
5258                 .key      = osd_it_ea_key,
5259                 .key_size = osd_it_ea_key_size,
5260                 .rec      = osd_it_ea_rec,
5261                 .store    = osd_it_ea_store,
5262                 .load     = osd_it_ea_load
5263         }
5264 };
5265
5266 static void *osd_key_init(const struct lu_context *ctx,
5267                           struct lu_context_key *key)
5268 {
5269         struct osd_thread_info *info;
5270
5271         OBD_ALLOC_PTR(info);
5272         if (info == NULL)
5273                 return ERR_PTR(-ENOMEM);
5274
5275         OBD_ALLOC(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5276         if (info->oti_it_ea_buf == NULL)
5277                 goto out_free_info;
5278
5279         info->oti_env = container_of(ctx, struct lu_env, le_ctx);
5280
5281         info->oti_hlock = ldiskfs_htree_lock_alloc();
5282         if (info->oti_hlock == NULL)
5283                 goto out_free_ea;
5284
5285         return info;
5286
5287  out_free_ea:
5288         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5289  out_free_info:
5290         OBD_FREE_PTR(info);
5291         return ERR_PTR(-ENOMEM);
5292 }
5293
5294 static void osd_key_fini(const struct lu_context *ctx,
5295                          struct lu_context_key *key, void* data)
5296 {
5297         struct osd_thread_info *info = data;
5298
5299         if (info->oti_hlock != NULL)
5300                 ldiskfs_htree_lock_free(info->oti_hlock);
5301         OBD_FREE(info->oti_it_ea_buf, OSD_IT_EA_BUFSIZE);
5302         lu_buf_free(&info->oti_iobuf.dr_pg_buf);
5303         lu_buf_free(&info->oti_iobuf.dr_bl_buf);
5304         OBD_FREE_PTR(info);
5305 }
5306
5307 static void osd_key_exit(const struct lu_context *ctx,
5308                          struct lu_context_key *key, void *data)
5309 {
5310         struct osd_thread_info *info = data;
5311
5312         LASSERT(info->oti_r_locks == 0);
5313         LASSERT(info->oti_w_locks == 0);
5314         LASSERT(info->oti_txns    == 0);
5315 }
5316
5317 /* type constructor/destructor: osd_type_init, osd_type_fini */
5318 LU_TYPE_INIT_FINI(osd, &osd_key);
5319
5320 struct lu_context_key osd_key = {
5321         .lct_tags = LCT_DT_THREAD | LCT_MD_THREAD | LCT_MG_THREAD | LCT_LOCAL,
5322         .lct_init = osd_key_init,
5323         .lct_fini = osd_key_fini,
5324         .lct_exit = osd_key_exit
5325 };
5326
5327
5328 static int osd_device_init(const struct lu_env *env, struct lu_device *d,
5329                            const char *name, struct lu_device *next)
5330 {
5331         struct osd_device *osd = osd_dev(d);
5332
5333         if (strlcpy(osd->od_svname, name, sizeof(osd->od_svname))
5334             >= sizeof(osd->od_svname))
5335                 return -E2BIG;
5336         return osd_procfs_init(osd, name);
5337 }
5338
5339 static int osd_shutdown(const struct lu_env *env, struct osd_device *o)
5340 {
5341         ENTRY;
5342
5343         /* shutdown quota slave instance associated with the device */
5344         if (o->od_quota_slave != NULL) {
5345                 qsd_fini(env, o->od_quota_slave);
5346                 o->od_quota_slave = NULL;
5347         }
5348
5349         RETURN(0);
5350 }
5351
5352 static void osd_umount(const struct lu_env *env, struct osd_device *o)
5353 {
5354         ENTRY;
5355
5356         if (o->od_fsops) {
5357                 fsfilt_put_ops(o->od_fsops);
5358                 o->od_fsops = NULL;
5359         }
5360
5361         if (o->od_mnt != NULL) {
5362                 shrink_dcache_sb(osd_sb(o));
5363                 osd_sync(env, &o->od_dt_dev);
5364
5365                 mntput(o->od_mnt);
5366                 o->od_mnt = NULL;
5367         }
5368
5369         EXIT;
5370 }
5371
5372 static int osd_mount(const struct lu_env *env,
5373                      struct osd_device *o, struct lustre_cfg *cfg)
5374 {
5375         const char              *name  = lustre_cfg_string(cfg, 0);
5376         const char              *dev  = lustre_cfg_string(cfg, 1);
5377         const char              *opts;
5378         unsigned long            page, s_flags, lmd_flags = 0;
5379         struct page             *__page;
5380         struct file_system_type *type;
5381         char                    *options = NULL;
5382         char                    *str;
5383         struct osd_thread_info  *info = osd_oti_get(env);
5384         struct lu_fid           *fid = &info->oti_fid;
5385         struct inode            *inode;
5386         int                      rc = 0;
5387         ENTRY;
5388
5389         if (o->od_mnt != NULL)
5390                 RETURN(0);
5391
5392         if (strlen(dev) >= sizeof(o->od_mntdev))
5393                 RETURN(-E2BIG);
5394         strcpy(o->od_mntdev, dev);
5395
5396         o->od_fsops = fsfilt_get_ops(mt_str(LDD_MT_LDISKFS));
5397         if (IS_ERR(o->od_fsops)) {
5398                 CERROR("%s: Can't find fsfilt_ldiskfs\n", name);
5399                 o->od_fsops = NULL;
5400                 RETURN(-ENOTSUPP);
5401         }
5402
5403         OBD_PAGE_ALLOC(__page, GFP_IOFS);
5404         if (__page == NULL)
5405                 GOTO(out, rc = -ENOMEM);
5406
5407         str = lustre_cfg_string(cfg, 2);
5408         s_flags = simple_strtoul(str, NULL, 0);
5409         str = strstr(str, ":");
5410         if (str)
5411                 lmd_flags = simple_strtoul(str + 1, NULL, 0);
5412         opts = lustre_cfg_string(cfg, 3);
5413         page = (unsigned long)page_address(__page);
5414         options = (char *)page;
5415         *options = '\0';
5416         if (opts == NULL)
5417                 strcat(options, "user_xattr,acl");
5418         else
5419                 strcat(options, opts);
5420
5421         /* Glom up mount options */
5422         if (*options != '\0')
5423                 strcat(options, ",");
5424         strlcat(options, "no_mbcache", PAGE_CACHE_SIZE);
5425
5426         type = get_fs_type("ldiskfs");
5427         if (!type) {
5428                 CERROR("%s: cannot find ldiskfs module\n", name);
5429                 GOTO(out, rc = -ENODEV);
5430         }
5431
5432         o->od_mnt = vfs_kern_mount(type, s_flags, dev, options);
5433         cfs_module_put(type->owner);
5434
5435         if (IS_ERR(o->od_mnt)) {
5436                 rc = PTR_ERR(o->od_mnt);
5437                 o->od_mnt = NULL;
5438                 CERROR("%s: can't mount %s: %d\n", name, dev, rc);
5439                 GOTO(out, rc);
5440         }
5441
5442 #ifdef HAVE_DEV_SET_RDONLY
5443         if (dev_check_rdonly(o->od_mnt->mnt_sb->s_bdev)) {
5444                 CERROR("%s: underlying device %s is marked as read-only. "
5445                        "Setup failed\n", name, dev);
5446                 GOTO(out_mnt, rc = -EROFS);
5447         }
5448 #endif
5449
5450         if (!LDISKFS_HAS_COMPAT_FEATURE(o->od_mnt->mnt_sb,
5451             LDISKFS_FEATURE_COMPAT_HAS_JOURNAL)) {
5452                 CERROR("%s: device %s is mounted w/o journal\n", name, dev);
5453                 GOTO(out_mnt, rc = -EINVAL);
5454         }
5455
5456         inode = osd_sb(o)->s_root->d_inode;
5457         ldiskfs_set_inode_state(inode, LDISKFS_STATE_LUSTRE_NO_OI);
5458         lu_local_obj_fid(fid, OSD_FS_ROOT_OID);
5459         rc = osd_ea_fid_set(info, inode, fid, LMAC_NOT_IN_OI, 0);
5460         if (rc != 0) {
5461                 CERROR("%s: failed to set lma on %s root inode\n", name, dev);
5462                 GOTO(out_mnt, rc);
5463         }
5464
5465         if (lmd_flags & LMD_FLG_NOSCRUB)
5466                 o->od_noscrub = 1;
5467
5468         GOTO(out, rc = 0);
5469
5470 out_mnt:
5471         mntput(o->od_mnt);
5472         o->od_mnt = NULL;
5473
5474 out:
5475         if (__page)
5476                 OBD_PAGE_FREE(__page);
5477         if (rc)
5478                 fsfilt_put_ops(o->od_fsops);
5479
5480         return rc;
5481 }
5482
5483 static struct lu_device *osd_device_fini(const struct lu_env *env,
5484                                          struct lu_device *d)
5485 {
5486         struct osd_device *o = osd_dev(d);
5487         ENTRY;
5488
5489         osd_procfs_fini(o);
5490         osd_shutdown(env, o);
5491         osd_scrub_cleanup(env, o);
5492         osd_obj_map_fini(o);
5493         osd_umount(env, o);
5494
5495         RETURN(NULL);
5496 }
5497
5498 static int osd_device_init0(const struct lu_env *env,
5499                             struct osd_device *o,
5500                             struct lustre_cfg *cfg)
5501 {
5502         struct lu_device        *l = osd2lu_dev(o);
5503         struct osd_thread_info *info;
5504         int                     rc;
5505         int                     cplen = 0;
5506
5507         /* if the module was re-loaded, env can loose its keys */
5508         rc = lu_env_refill((struct lu_env *) env);
5509         if (rc)
5510                 GOTO(out, rc);
5511         info = osd_oti_get(env);
5512         LASSERT(info);
5513
5514         l->ld_ops = &osd_lu_ops;
5515         o->od_dt_dev.dd_ops = &osd_dt_ops;
5516
5517         spin_lock_init(&o->od_osfs_lock);
5518         mutex_init(&o->od_otable_mutex);
5519         o->od_osfs_age = cfs_time_shift_64(-1000);
5520
5521         o->od_capa_hash = init_capa_hash();
5522         if (o->od_capa_hash == NULL)
5523                 GOTO(out, rc = -ENOMEM);
5524
5525         o->od_read_cache = 1;
5526         o->od_writethrough_cache = 1;
5527         o->od_readcache_max_filesize = OSD_MAX_CACHE_SIZE;
5528
5529         rc = osd_mount(env, o, cfg);
5530         if (rc)
5531                 GOTO(out_capa, rc);
5532
5533         cplen = strlcpy(o->od_svname, lustre_cfg_string(cfg, 4),
5534                         sizeof(o->od_svname));
5535         if (cplen >= sizeof(o->od_svname)) {
5536                 rc = -E2BIG;
5537                 GOTO(out_mnt, rc);
5538         }
5539
5540         rc = osd_obj_map_init(env, o);
5541         if (rc != 0)
5542                 GOTO(out_mnt, rc);
5543
5544         rc = lu_site_init(&o->od_site, l);
5545         if (rc != 0)
5546                 GOTO(out_compat, rc);
5547         o->od_site.ls_bottom_dev = l;
5548
5549         rc = lu_site_init_finish(&o->od_site);
5550         if (rc != 0)
5551                 GOTO(out_site, rc);
5552
5553         CFS_INIT_LIST_HEAD(&o->od_ios_list);
5554         /* setup scrub, including OI files initialization */
5555         rc = osd_scrub_setup(env, o);
5556         if (rc < 0)
5557                 GOTO(out_site, rc);
5558
5559         rc = osd_procfs_init(o, o->od_svname);
5560         if (rc != 0) {
5561                 CERROR("%s: can't initialize procfs: rc = %d\n",
5562                        o->od_svname, rc);
5563                 GOTO(out_scrub, rc);
5564         }
5565
5566         LASSERT(l->ld_site->ls_linkage.next && l->ld_site->ls_linkage.prev);
5567
5568         /* initialize quota slave instance */
5569         o->od_quota_slave = qsd_init(env, o->od_svname, &o->od_dt_dev,
5570                                      o->od_proc_entry);
5571         if (IS_ERR(o->od_quota_slave)) {
5572                 rc = PTR_ERR(o->od_quota_slave);
5573                 o->od_quota_slave = NULL;
5574                 GOTO(out_procfs, rc);
5575         }
5576
5577         RETURN(0);
5578
5579 out_procfs:
5580         osd_procfs_fini(o);
5581 out_scrub:
5582         osd_scrub_cleanup(env, o);
5583 out_site:
5584         lu_site_fini(&o->od_site);
5585 out_compat:
5586         osd_obj_map_fini(o);
5587 out_mnt:
5588         osd_umount(env, o);
5589 out_capa:
5590         cleanup_capa_hash(o->od_capa_hash);
5591 out:
5592         return rc;
5593 }
5594
5595 static struct lu_device *osd_device_alloc(const struct lu_env *env,
5596                                           struct lu_device_type *t,
5597                                           struct lustre_cfg *cfg)
5598 {
5599         struct osd_device *o;
5600         int                rc;
5601
5602         OBD_ALLOC_PTR(o);
5603         if (o == NULL)
5604                 return ERR_PTR(-ENOMEM);
5605
5606         rc = dt_device_init(&o->od_dt_dev, t);
5607         if (rc == 0) {
5608                 /* Because the ctx might be revived in dt_device_init,
5609                  * refill the env here */
5610                 lu_env_refill((struct lu_env *)env);
5611                 rc = osd_device_init0(env, o, cfg);
5612                 if (rc)
5613                         dt_device_fini(&o->od_dt_dev);
5614         }
5615
5616         if (unlikely(rc != 0))
5617                 OBD_FREE_PTR(o);
5618
5619         return rc == 0 ? osd2lu_dev(o) : ERR_PTR(rc);
5620 }
5621
5622 static struct lu_device *osd_device_free(const struct lu_env *env,
5623                                          struct lu_device *d)
5624 {
5625         struct osd_device *o = osd_dev(d);
5626         ENTRY;
5627
5628         cleanup_capa_hash(o->od_capa_hash);
5629         /* XXX: make osd top device in order to release reference */
5630         d->ld_site->ls_top_dev = d;
5631         lu_site_purge(env, d->ld_site, -1);
5632         if (!cfs_hash_is_empty(d->ld_site->ls_obj_hash)) {
5633                 LIBCFS_DEBUG_MSG_DATA_DECL(msgdata, D_ERROR, NULL);
5634                 lu_site_print(env, d->ld_site, &msgdata, lu_cdebug_printer);
5635         }
5636         lu_site_fini(&o->od_site);
5637         dt_device_fini(&o->od_dt_dev);
5638         OBD_FREE_PTR(o);
5639         RETURN(NULL);
5640 }
5641
5642 static int osd_process_config(const struct lu_env *env,
5643                               struct lu_device *d, struct lustre_cfg *cfg)
5644 {
5645         struct osd_device *o = osd_dev(d);
5646         int err;
5647         ENTRY;
5648
5649         switch(cfg->lcfg_command) {
5650         case LCFG_SETUP:
5651                 err = osd_mount(env, o, cfg);
5652                 break;
5653         case LCFG_CLEANUP:
5654                 lu_dev_del_linkage(d->ld_site, d);
5655                 err = osd_shutdown(env, o);
5656                 break;
5657         default:
5658                 err = -ENOSYS;
5659         }
5660
5661         RETURN(err);
5662 }
5663
5664 static int osd_recovery_complete(const struct lu_env *env,
5665                                  struct lu_device *d)
5666 {
5667         struct osd_device       *osd = osd_dev(d);
5668         int                      rc = 0;
5669         ENTRY;
5670
5671         if (osd->od_quota_slave == NULL)
5672                 RETURN(0);
5673
5674         /* start qsd instance on recovery completion, this notifies the quota
5675          * slave code that we are about to process new requests now */
5676         rc = qsd_start(env, osd->od_quota_slave);
5677         RETURN(rc);
5678 }
5679
5680 /*
5681  * we use exports to track all osd users
5682  */
5683 static int osd_obd_connect(const struct lu_env *env, struct obd_export **exp,
5684                            struct obd_device *obd, struct obd_uuid *cluuid,
5685                            struct obd_connect_data *data, void *localdata)
5686 {
5687         struct osd_device    *osd = osd_dev(obd->obd_lu_dev);
5688         struct lustre_handle  conn;
5689         int                   rc;
5690         ENTRY;
5691
5692         CDEBUG(D_CONFIG, "connect #%d\n", osd->od_connects);
5693
5694         rc = class_connect(&conn, obd, cluuid);
5695         if (rc)
5696                 RETURN(rc);
5697
5698         *exp = class_conn2export(&conn);
5699
5700         spin_lock(&osd->od_osfs_lock);
5701         osd->od_connects++;
5702         spin_unlock(&osd->od_osfs_lock);
5703
5704         RETURN(0);
5705 }
5706
5707 /*
5708  * once last export (we don't count self-export) disappeared
5709  * osd can be released
5710  */
5711 static int osd_obd_disconnect(struct obd_export *exp)
5712 {
5713         struct obd_device *obd = exp->exp_obd;
5714         struct osd_device *osd = osd_dev(obd->obd_lu_dev);
5715         int                rc, release = 0;
5716         ENTRY;
5717
5718         /* Only disconnect the underlying layers on the final disconnect. */
5719         spin_lock(&osd->od_osfs_lock);
5720         osd->od_connects--;
5721         if (osd->od_connects == 0)
5722                 release = 1;
5723         spin_unlock(&osd->od_osfs_lock);
5724
5725         rc = class_disconnect(exp); /* bz 9811 */
5726
5727         if (rc == 0 && release)
5728                 class_manual_cleanup(obd);
5729         RETURN(rc);
5730 }
5731
5732 static int osd_prepare(const struct lu_env *env, struct lu_device *pdev,
5733                        struct lu_device *dev)
5734 {
5735         struct osd_device *osd = osd_dev(dev);
5736         int                result = 0;
5737         ENTRY;
5738
5739         if (osd->od_quota_slave != NULL)
5740                 /* set up quota slave objects */
5741                 result = qsd_prepare(env, osd->od_quota_slave);
5742
5743         RETURN(result);
5744 }
5745
5746 static const struct lu_object_operations osd_lu_obj_ops = {
5747         .loo_object_init      = osd_object_init,
5748         .loo_object_delete    = osd_object_delete,
5749         .loo_object_release   = osd_object_release,
5750         .loo_object_free      = osd_object_free,
5751         .loo_object_print     = osd_object_print,
5752         .loo_object_invariant = osd_object_invariant
5753 };
5754
5755 const struct lu_device_operations osd_lu_ops = {
5756         .ldo_object_alloc      = osd_object_alloc,
5757         .ldo_process_config    = osd_process_config,
5758         .ldo_recovery_complete = osd_recovery_complete,
5759         .ldo_prepare           = osd_prepare,
5760 };
5761
5762 static const struct lu_device_type_operations osd_device_type_ops = {
5763         .ldto_init = osd_type_init,
5764         .ldto_fini = osd_type_fini,
5765
5766         .ldto_start = osd_type_start,
5767         .ldto_stop  = osd_type_stop,
5768
5769         .ldto_device_alloc = osd_device_alloc,
5770         .ldto_device_free  = osd_device_free,
5771
5772         .ldto_device_init    = osd_device_init,
5773         .ldto_device_fini    = osd_device_fini
5774 };
5775
5776 struct lu_device_type osd_device_type = {
5777         .ldt_tags     = LU_DEVICE_DT,
5778         .ldt_name     = LUSTRE_OSD_LDISKFS_NAME,
5779         .ldt_ops      = &osd_device_type_ops,
5780         .ldt_ctx_tags = LCT_LOCAL,
5781 };
5782
5783 /*
5784  * lprocfs legacy support.
5785  */
5786 static struct obd_ops osd_obd_device_ops = {
5787         .o_owner = THIS_MODULE,
5788         .o_connect      = osd_obd_connect,
5789         .o_disconnect   = osd_obd_disconnect
5790 };
5791
5792 static int __init osd_mod_init(void)
5793 {
5794         struct lprocfs_static_vars lvars;
5795
5796         osd_oi_mod_init();
5797         lprocfs_osd_init_vars(&lvars);
5798         return class_register_type(&osd_obd_device_ops, NULL, lvars.module_vars,
5799                                    LUSTRE_OSD_LDISKFS_NAME, &osd_device_type);
5800 }
5801
5802 static void __exit osd_mod_exit(void)
5803 {
5804         class_unregister_type(LUSTRE_OSD_LDISKFS_NAME);
5805 }
5806
5807 MODULE_AUTHOR("Sun Microsystems, Inc. <http://www.lustre.org/>");
5808 MODULE_DESCRIPTION("Lustre Object Storage Device ("LUSTRE_OSD_LDISKFS_NAME")");
5809 MODULE_LICENSE("GPL");
5810
5811 cfs_module(osd, "0.1.0", osd_mod_init, osd_mod_exit);