Whamcloud - gitweb
509b0dffcf3a0edc93a4462f1962212afeff9790
[fs/lustre-release.git] / lustre / lod / lod_qos.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,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License version 2 for more details.  A copy is
14  * included in the COPYING file that accompanied this code.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19  *
20  * GPL HEADER END
21  */
22 /*
23  * Copyright  2009 Sun Microsystems, Inc. All rights reserved
24  * Use is subject to license terms.
25  *
26  * Copyright (c) 2012, 2017, Intel Corporation.
27  */
28 /*
29  * This file is part of Lustre, http://www.lustre.org/
30  * Lustre is a trademark of Sun Microsystems, Inc.
31  *
32  * lustre/lod/lod_qos.c
33  *
34  * Implementation of different allocation algorithm used
35  * to distribute objects and data among OSTs.
36  */
37
38 #define DEBUG_SUBSYSTEM S_LOV
39
40 #include <asm/div64.h>
41 #include <linux/random.h>
42
43 #include <libcfs/libcfs.h>
44 #include <uapi/linux/lustre/lustre_idl.h>
45 #include <lustre_swab.h>
46 #include <obd_class.h>
47
48 #include "lod_internal.h"
49
50 /*
51  * force QoS policy (not RR) to be used for testing purposes
52  */
53 #define FORCE_QOS_
54
55 #define D_QOS   D_OTHER
56
57 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_QOS, fmt, ## __VA_ARGS__)
58 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_QOS, fmt, ## __VA_ARGS__)
59
60 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
61                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
62
63 static inline int lod_statfs_check(struct lu_tgt_descs *ltd,
64                                    struct lu_tgt_desc *tgt)
65 {
66         struct obd_statfs *sfs = &tgt->ltd_statfs;
67
68         if (((sfs->os_state & OS_STATFS_ENOSPC) ||
69             (!ltd->ltd_is_mdt && sfs->os_state & OS_STATFS_ENOINO &&
70              sfs->os_fprecreated == 0)))
71                 return -ENOSPC;
72
73         /* If the OST is readonly then we can't allocate objects there */
74         if (sfs->os_state & OS_STATFS_READONLY)
75                 return -EROFS;
76
77         /* object precreation is skipped on the OST with max_create_count=0 */
78         if (!ltd->ltd_is_mdt && sfs->os_state & OS_STATFS_NOPRECREATE)
79                 return -ENOBUFS;
80
81         return 0;
82 }
83
84 /**
85  * Check whether the target is available for new objects.
86  *
87  * Request statfs data from the given target and verify it's active and not
88  * read-only. If so, then it can be used to place new objects. This
89  * function also maintains the number of active/inactive targets and sets
90  * dirty flags if those numbers change so others can run re-balance procedures.
91  * No external locking is required.
92  *
93  * \param[in] env       execution environment for this thread
94  * \param[in] d         LOD device
95  * \param[in] ltd       target table
96  * \param[in] tgt       target
97  *
98  * \retval 0            if the target is good
99  * \retval negative     negated errno on error
100  */
101 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
102                                 struct lu_tgt_descs *ltd,
103                                 struct lu_tgt_desc *tgt)
104 {
105         struct lov_desc *desc = &ltd->ltd_lov_desc;
106         int rc;
107         ENTRY;
108
109         LASSERT(d);
110         LASSERT(tgt);
111
112         rc = dt_statfs(env, tgt->ltd_tgt, &tgt->ltd_statfs);
113         if (rc && rc != -ENOTCONN)
114                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
115
116         if (!rc) {
117                 rc = lod_statfs_check(ltd, tgt);
118                 if (rc == -ENOSPC)
119                         return rc;
120         }
121
122         /* check whether device has changed state (active, inactive) */
123         if (rc != 0 && tgt->ltd_active) {
124                 /* turned inactive? */
125                 spin_lock(&d->lod_lock);
126                 if (tgt->ltd_active) {
127                         tgt->ltd_active = 0;
128                         if (rc == -ENOTCONN)
129                                 tgt->ltd_connecting = 1;
130
131                         LASSERT(desc->ld_active_tgt_count > 0);
132                         desc->ld_active_tgt_count--;
133                         ltd->ltd_qos.lq_dirty = 1;
134                         ltd->ltd_qos.lq_rr.lqr_dirty = 1;
135                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
136                                tgt->ltd_exp->exp_obd->obd_name);
137                 }
138                 spin_unlock(&d->lod_lock);
139         } else if (rc == 0 && tgt->ltd_active == 0) {
140                 /* turned active? */
141                 LASSERTF(desc->ld_active_tgt_count < desc->ld_tgt_count,
142                          "active tgt count %d, tgt nr %d\n",
143                          desc->ld_active_tgt_count, desc->ld_tgt_count);
144                 spin_lock(&d->lod_lock);
145                 if (tgt->ltd_active == 0) {
146                         tgt->ltd_active = 1;
147                         tgt->ltd_connecting = 0;
148                         desc->ld_active_tgt_count++;
149                         ltd->ltd_qos.lq_dirty = 1;
150                         ltd->ltd_qos.lq_rr.lqr_dirty = 1;
151                         CDEBUG(D_CONFIG, "%s: turns active\n",
152                                tgt->ltd_exp->exp_obd->obd_name);
153                 }
154                 spin_unlock(&d->lod_lock);
155         }
156         if (rc == -ENOTCONN) {
157                 /* In case that the ENOTCONN for inactive OST state is
158                  * mistreated as MDT disconnection state by the client,
159                  * this error should be changed to someone else.
160                  */
161                 rc = -EREMOTEIO;
162         }
163
164         RETURN(rc);
165 }
166
167 static int lod_is_tgt_usable(struct lu_tgt_descs *ltd, struct lu_tgt_desc *tgt)
168 {
169         int rc;
170
171         rc = lod_statfs_check(ltd, tgt);
172         if (rc)
173                 return rc;
174
175         if (!tgt->ltd_active)
176                 return -ENOTCONN;
177
178         return 0;
179 }
180
181 /**
182  * Maintain per-target statfs data.
183  *
184  * The function refreshes statfs data for all the targets every N seconds.
185  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
186  * initially.
187  *
188  * \param[in] env       execution environment for this thread
189  * \param[in] lod       LOD device
190  * \param[in] ltd       tgt table
191  */
192 void lod_qos_statfs_update(const struct lu_env *env, struct lod_device *lod,
193                            struct lu_tgt_descs *ltd)
194 {
195         struct obd_device *obd = lod2obd(lod);
196         struct lu_tgt_desc *tgt;
197         time64_t max_age;
198         u64 avail;
199         ENTRY;
200
201         max_age = ktime_get_seconds() - 2 * ltd->ltd_lov_desc.ld_qos_maxage;
202
203         if (obd->obd_osfs_age > max_age)
204                 /* statfs data are quite recent, don't need to refresh it */
205                 RETURN_EXIT;
206
207         down_write(&ltd->ltd_qos.lq_rw_sem);
208
209         if (obd->obd_osfs_age > max_age)
210                 goto out;
211
212         ltd_foreach_tgt(ltd, tgt) {
213                 avail = tgt->ltd_statfs.os_bavail;
214                 if (lod_statfs_and_check(env, lod, ltd, tgt))
215                         continue;
216
217                 if (tgt->ltd_statfs.os_bavail != avail)
218                         /* recalculate weigths */
219                         ltd->ltd_qos.lq_dirty = 1;
220         }
221         obd->obd_osfs_age = ktime_get_seconds();
222
223 out:
224         up_write(&ltd->ltd_qos.lq_rw_sem);
225         EXIT;
226 }
227
228 #define LOV_QOS_EMPTY ((__u32)-1)
229
230 /**
231  * Calculate optimal round-robin order with regard to OSSes.
232  *
233  * Place all the OSTs from pool \a src_pool in a special array to be used for
234  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
235  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
236  * Resorts the targets when the number of active targets changes (because of
237  * a new target or activation/deactivation).
238  *
239  * \param[in] lod       LOD device
240  * \param[in] ltd       tgt table
241  * \param[in] src_pool  tgt pool
242  * \param[in] lqr       round-robin list
243  *
244  * \retval 0            on success
245  * \retval -ENOMEM      fails to allocate the array
246  */
247 static int lod_qos_calc_rr(struct lod_device *lod, struct lu_tgt_descs *ltd,
248                            const struct lu_tgt_pool *src_pool,
249                            struct lu_qos_rr *lqr)
250 {
251         struct lu_svr_qos  *svr;
252         struct lu_tgt_desc *tgt;
253         unsigned placed, real_count;
254         unsigned int i;
255         int rc;
256         ENTRY;
257
258         if (!lqr->lqr_dirty) {
259                 LASSERT(lqr->lqr_pool.op_size);
260                 RETURN(0);
261         }
262
263         /* Do actual allocation. */
264         down_write(&ltd->ltd_qos.lq_rw_sem);
265
266         /*
267          * Check again. While we were sleeping on @lq_rw_sem something could
268          * change.
269          */
270         if (!lqr->lqr_dirty) {
271                 LASSERT(lqr->lqr_pool.op_size);
272                 up_write(&ltd->ltd_qos.lq_rw_sem);
273                 RETURN(0);
274         }
275
276         real_count = src_pool->op_count;
277
278         /* Zero the pool array */
279         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
280            deleting from the pool. The lq_rw_sem insures that nobody else
281            is reading. */
282         lqr->lqr_pool.op_count = real_count;
283         rc = tgt_pool_extend(&lqr->lqr_pool, real_count);
284         if (rc) {
285                 up_write(&ltd->ltd_qos.lq_rw_sem);
286                 RETURN(rc);
287         }
288         for (i = 0; i < lqr->lqr_pool.op_count; i++)
289                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
290
291         /* Place all the tgts from 1 svr at the same time. */
292         placed = 0;
293         list_for_each_entry(svr, &ltd->ltd_qos.lq_svr_list, lsq_svr_list) {
294                 int j = 0;
295
296                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
297                         int next;
298
299                         if (!cfs_bitmap_check(ltd->ltd_tgt_bitmap,
300                                               src_pool->op_array[i]))
301                                 continue;
302
303                         tgt = LTD_TGT(ltd, src_pool->op_array[i]);
304                         LASSERT(tgt && tgt->ltd_tgt);
305                         if (tgt->ltd_qos.ltq_svr != svr)
306                                 continue;
307
308                         /* Evenly space these tgts across arrayspace */
309                         next = j * lqr->lqr_pool.op_count / svr->lsq_tgt_count;
310                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
311                                 next = (next + 1) % lqr->lqr_pool.op_count;
312
313                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
314                         j++;
315                         placed++;
316                 }
317         }
318
319         lqr->lqr_dirty = 0;
320         up_write(&ltd->ltd_qos.lq_rw_sem);
321
322         if (placed != real_count) {
323                 /* This should never happen */
324                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all tgts in the "
325                                    "round-robin list (%d of %d).\n",
326                                    placed, real_count);
327                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
328                         LCONSOLE(D_WARNING, "rr #%d tgt idx=%d\n", i,
329                                  lqr->lqr_pool.op_array[i]);
330                 }
331                 lqr->lqr_dirty = 1;
332                 RETURN(-EAGAIN);
333         }
334
335 #if 0
336         for (i = 0; i < lqr->lqr_pool.op_count; i++)
337                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
338 #endif
339
340         RETURN(0);
341 }
342
343 /**
344  * Instantiate and declare creation of a new object.
345  *
346  * The function instantiates LU representation for a new object on the
347  * specified device. Also it declares an intention to create that
348  * object on the storage target.
349  *
350  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
351  * infrastructure - in the existing precreation framework we can't assign FID
352  * at this moment, we do this later once a transaction is started. So the
353  * special method instantiates FID-less object in the cache and later it
354  * will get a FID and proper placement in LU cache.
355  *
356  * \param[in] env       execution environment for this thread
357  * \param[in] d         LOD device
358  * \param[in] ost_idx   OST target index where the object is being created
359  * \param[in] th        transaction handle
360  *
361  * \retval              object ptr on success, ERR_PTR() otherwise
362  */
363 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
364                                                    struct lod_device *d,
365                                                    __u32 ost_idx,
366                                                    struct thandle *th)
367 {
368         struct lod_tgt_desc *ost;
369         struct lu_object *o, *n;
370         struct lu_device *nd;
371         struct dt_object *dt;
372         int               rc;
373         ENTRY;
374
375         LASSERT(d);
376         LASSERT(ost_idx < d->lod_ost_descs.ltd_tgts_size);
377         ost = OST_TGT(d,ost_idx);
378         LASSERT(ost);
379         LASSERT(ost->ltd_tgt);
380
381         nd = &ost->ltd_tgt->dd_lu_dev;
382
383         /*
384          * allocate anonymous object with zero fid, real fid
385          * will be assigned by OSP within transaction
386          * XXX: to be fixed with fully-functional OST fids
387          */
388         o = lu_object_anon(env, nd, NULL);
389         if (IS_ERR(o))
390                 GOTO(out, dt = ERR_PTR(PTR_ERR(o)));
391
392         n = lu_object_locate(o->lo_header, nd->ld_type);
393         if (unlikely(n == NULL)) {
394                 CERROR("can't find slice\n");
395                 lu_object_put(env, o);
396                 GOTO(out, dt = ERR_PTR(-EINVAL));
397         }
398
399         dt = container_of(n, struct dt_object, do_lu);
400
401         rc = lod_sub_declare_create(env, dt, NULL, NULL, NULL, th);
402         if (rc < 0) {
403                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
404                        ost_idx, rc);
405                 lu_object_put(env, o);
406                 dt = ERR_PTR(rc);
407         }
408
409 out:
410         RETURN(dt);
411 }
412
413 /**
414  * Calculate a minimum acceptable stripe count.
415  *
416  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
417  * all stripes or 3/4 of stripes.
418  *
419  * \param[in] stripe_count      number of stripes requested
420  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
421  *
422  * \retval                      acceptable stripecount
423  */
424 static int min_stripe_count(__u32 stripe_count, int flags)
425 {
426         return (flags & LOV_USES_DEFAULT_STRIPE ?
427                 stripe_count - (stripe_count / 4) : stripe_count);
428 }
429
430 #define LOV_CREATE_RESEED_MULT 30
431 #define LOV_CREATE_RESEED_MIN  2000
432
433 /**
434  * Initialize temporary tgt-in-use array.
435  *
436  * Allocate or extend the array used to mark targets already assigned to a new
437  * striping so they are not used more than once.
438  *
439  * \param[in] env       execution environment for this thread
440  * \param[in] stripes   number of items needed in the array
441  *
442  * \retval 0            on success
443  * \retval -ENOMEM      on error
444  */
445 static inline int lod_qos_tgt_in_use_clear(const struct lu_env *env,
446                                            __u32 stripes)
447 {
448         struct lod_thread_info *info = lod_env_info(env);
449
450         if (info->lti_ea_store_size < sizeof(int) * stripes)
451                 lod_ea_store_resize(info, stripes * sizeof(int));
452         if (info->lti_ea_store_size < sizeof(int) * stripes) {
453                 CERROR("can't allocate memory for tgt-in-use array\n");
454                 return -ENOMEM;
455         }
456         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
457         return 0;
458 }
459
460 /**
461  * Remember a target in the array of used targets.
462  *
463  * Mark the given target as used for a new striping being created. The status
464  * of an tgt in a striping can be checked with lod_qos_is_tgt_used().
465  *
466  * \param[in] env       execution environment for this thread
467  * \param[in] idx       index in the array
468  * \param[in] tgt_idx   target index to mark as used
469  */
470 static inline void lod_qos_tgt_in_use(const struct lu_env *env,
471                                       int idx, int tgt_idx)
472 {
473         struct lod_thread_info *info = lod_env_info(env);
474         int *tgts = info->lti_ea_store;
475
476         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
477         tgts[idx] = tgt_idx;
478 }
479
480 /**
481  * Check is tgt used in a striping.
482  *
483  * Checks whether tgt with the given index is marked as used in the temporary
484  * array (see lod_qos_tgt_in_use()).
485  *
486  * \param[in] env       execution environment for this thread
487  * \param[in] tgt_idx   target index to check
488  * \param[in] stripes   the number of items used in the array already
489  *
490  * \retval 0            not used
491  * \retval 1            used
492  */
493 static int lod_qos_is_tgt_used(const struct lu_env *env, int tgt_idx,
494                                __u32 stripes)
495 {
496         struct lod_thread_info *info = lod_env_info(env);
497         int *tgts = info->lti_ea_store;
498         __u32 j;
499
500         for (j = 0; j < stripes; j++) {
501                 if (tgts[j] == tgt_idx)
502                         return 1;
503         }
504         return 0;
505 }
506
507 static inline bool
508 lod_obj_is_ost_use_skip_cb(const struct lu_env *env, struct lod_object *lo,
509                            int comp_idx, struct lod_obj_stripe_cb_data *data)
510 {
511         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
512
513         return comp->llc_ost_indices == NULL;
514 }
515
516 static inline int
517 lod_obj_is_ost_use_cb(const struct lu_env *env, struct lod_object *lo,
518                       int comp_idx, struct lod_obj_stripe_cb_data *data)
519 {
520         struct lod_layout_component *comp = &lo->ldo_comp_entries[comp_idx];
521         int i;
522
523         for (i = 0; i < comp->llc_stripe_count; i++) {
524                 if (comp->llc_ost_indices[i] == data->locd_ost_index) {
525                         data->locd_ost_index = -1;
526                         return -EEXIST;
527                 }
528         }
529
530         return 0;
531 }
532
533 /**
534  * Check is OST used in a composite layout
535  *
536  * \param[in] lo        lod object
537  * \param[in] ost       OST target index to check
538  *
539  * \retval false        not used
540  * \retval true         used
541  */
542 static inline bool lod_comp_is_ost_used(const struct lu_env *env,
543                                        struct lod_object *lo, int ost)
544 {
545         struct lod_obj_stripe_cb_data data = { { 0 } };
546
547         data.locd_ost_index = ost;
548         data.locd_comp_skip_cb = lod_obj_is_ost_use_skip_cb;
549         data.locd_comp_cb = lod_obj_is_ost_use_cb;
550
551         (void)lod_obj_for_each_stripe(env, lo, NULL, &data);
552
553         return data.locd_ost_index == -1;
554 }
555
556 static inline void lod_avoid_update(struct lod_object *lo,
557                                     struct lod_avoid_guide *lag)
558 {
559         if (!lod_is_flr(lo))
560                 return;
561
562         lag->lag_ost_avail--;
563 }
564
565 static inline bool lod_should_avoid_ost(struct lod_object *lo,
566                                         struct lod_avoid_guide *lag,
567                                         __u32 index)
568 {
569         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
570         struct lod_tgt_desc *ost = OST_TGT(lod, index);
571         struct lu_svr_qos *lsq = ost->ltd_qos.ltq_svr;
572         bool used = false;
573         int i;
574
575         if (!cfs_bitmap_check(lod->lod_ost_bitmap, index)) {
576                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
577                           index);
578                 return true;
579         }
580
581         /**
582          * we've tried our best, all available OSTs have been used in
583          * overlapped components in the other mirror
584          */
585         if (lag->lag_ost_avail == 0)
586                 return false;
587
588         /* check OSS use */
589         for (i = 0; i < lag->lag_oaa_count; i++) {
590                 if (lag->lag_oss_avoid_array[i] == lsq->lsq_id) {
591                         used = true;
592                         break;
593                 }
594         }
595         /**
596          * if the OSS which OST[index] resides has not been used, we'd like to
597          * use it
598          */
599         if (!used)
600                 return false;
601
602         /* if the OSS has been used, check whether the OST has been used */
603         if (!cfs_bitmap_check(lag->lag_ost_avoid_bitmap, index))
604                 used = false;
605         else
606                 QOS_DEBUG("OST%d: been used in conflicting mirror component\n",
607                           index);
608         return used;
609 }
610
611 static int lod_check_and_reserve_ost(const struct lu_env *env,
612                                      struct lod_object *lo,
613                                      struct lod_layout_component *lod_comp,
614                                      __u32 ost_idx, __u32 speed, __u32 *s_idx,
615                                      struct dt_object **stripe,
616                                      __u32 *ost_indices,
617                                      struct thandle *th,
618                                      bool *overstriped)
619 {
620         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
621         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
622         struct lu_tgt_desc *ost = OST_TGT(lod, ost_idx);
623         struct dt_object   *o;
624         __u32 stripe_idx = *s_idx;
625         int rc;
626
627         ENTRY;
628
629         rc = lod_statfs_and_check(env, lod, &lod->lod_ost_descs, ost);
630         if (rc)
631                 RETURN(rc);
632
633         /*
634          * We expect number of precreated objects in f_ffree at
635          * the first iteration, skip OSPs with no objects ready
636          */
637         if (ost->ltd_statfs.os_fprecreated == 0 && speed == 0) {
638                 QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
639                 RETURN(rc);
640         }
641
642         /*
643          * try to use another OSP if this one is degraded
644          */
645         if (ost->ltd_statfs.os_state & OS_STATFS_DEGRADED && speed < 2) {
646                 QOS_DEBUG("#%d: degraded\n", ost_idx);
647                 RETURN(rc);
648         }
649
650         /*
651          * try not allocate on OST which has been used by other
652          * component
653          */
654         if (speed == 0 && lod_comp_is_ost_used(env, lo, ost_idx)) {
655                 QOS_DEBUG("iter %d: OST%d used by other component\n",
656                           speed, ost_idx);
657                 RETURN(rc);
658         }
659
660         /**
661          * try not allocate OSTs used by conflicting component of other mirrors
662          * for the first and second time.
663          */
664         if (speed < 2 && lod_should_avoid_ost(lo, lag, ost_idx)) {
665                 QOS_DEBUG("iter %d: OST%d used by conflicting mirror component\n",
666                           speed, ost_idx);
667                 RETURN(rc);
668         }
669
670         /* do not put >1 objects on a single OST, except for overstriping */
671         if (lod_qos_is_tgt_used(env, ost_idx, stripe_idx)) {
672                 if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
673                         *overstriped = true;
674                 else
675                         RETURN(rc);
676         }
677
678         o = lod_qos_declare_object_on(env, lod, ost_idx, th);
679         if (IS_ERR(o)) {
680                 CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
681                        ost_idx, (int) PTR_ERR(o));
682                 rc = PTR_ERR(o);
683                 RETURN(rc);
684         }
685
686         /*
687          * We've successfully declared (reserved) an object
688          */
689         lod_avoid_update(lo, lag);
690         lod_qos_tgt_in_use(env, stripe_idx, ost_idx);
691         stripe[stripe_idx] = o;
692         ost_indices[stripe_idx] = ost_idx;
693         OBD_FAIL_TIMEOUT(OBD_FAIL_MDS_LOV_CREATE_RACE, 2);
694         stripe_idx++;
695         *s_idx = stripe_idx;
696
697         RETURN(rc);
698 }
699
700 /**
701  * Allocate a striping using round-robin algorithm.
702  *
703  * Allocates a new striping using round-robin algorithm. The function refreshes
704  * all the internal structures (statfs cache, array of available OSTs sorted
705  * with regard to OSS, etc). The number of stripes required is taken from the
706  * object (must be prepared by the caller), but can change if the flag
707  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
708  * is trying to create a striping on the object in parallel. All the internal
709  * structures (like pools, etc) are protected and no additional locking is
710  * required. The function succeeds even if a single stripe is allocated. To save
711  * time we give priority to targets which already have objects precreated.
712  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
713  *
714  * \param[in] env               execution environment for this thread
715  * \param[in] lo                LOD object
716  * \param[out] stripe           striping created
717  * \param[out] ost_indices      ost indices of striping created
718  * \param[in] flags             allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
719  * \param[in] th                transaction handle
720  * \param[in] comp_idx          index of ldo_comp_entries
721  *
722  * \retval 0            on success
723  * \retval -ENOSPC      if not enough OSTs are found
724  * \retval negative     negated errno for other failures
725  */
726 static int lod_ost_alloc_rr(const struct lu_env *env, struct lod_object *lo,
727                             struct dt_object **stripe, __u32 *ost_indices,
728                             int flags, struct thandle *th, int comp_idx)
729 {
730         struct lod_layout_component *lod_comp;
731         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
732         struct pool_desc  *pool = NULL;
733         struct lu_tgt_pool *osts;
734         struct lu_qos_rr *lqr;
735         unsigned int i, array_idx;
736         __u32 ost_start_idx_temp;
737         __u32 stripe_idx = 0;
738         __u32 stripe_count, stripe_count_min, ost_idx;
739         int rc, speed = 0, ost_connecting = 0;
740         int stripes_per_ost = 1;
741         bool overstriped = false;
742         ENTRY;
743
744         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
745         lod_comp = &lo->ldo_comp_entries[comp_idx];
746         stripe_count = lod_comp->llc_stripe_count;
747         stripe_count_min = min_stripe_count(stripe_count, flags);
748
749         if (lod_comp->llc_pool != NULL)
750                 pool = lod_find_pool(m, lod_comp->llc_pool);
751
752         if (pool != NULL) {
753                 down_read(&pool_tgt_rw_sem(pool));
754                 osts = &(pool->pool_obds);
755                 lqr = &(pool->pool_rr);
756         } else {
757                 osts = &m->lod_ost_descs.ltd_tgt_pool;
758                 lqr = &(m->lod_ost_descs.ltd_qos.lq_rr);
759         }
760
761         rc = lod_qos_calc_rr(m, &m->lod_ost_descs, osts, lqr);
762         if (rc)
763                 GOTO(out, rc);
764
765         rc = lod_qos_tgt_in_use_clear(env, stripe_count);
766         if (rc)
767                 GOTO(out, rc);
768
769         down_read(&m->lod_ost_descs.ltd_qos.lq_rw_sem);
770         spin_lock(&lqr->lqr_alloc);
771         if (--lqr->lqr_start_count <= 0) {
772                 lqr->lqr_start_idx = prandom_u32_max(osts->op_count);
773                 lqr->lqr_start_count =
774                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
775                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
776         } else if (stripe_count_min >= osts->op_count ||
777                         lqr->lqr_start_idx > osts->op_count) {
778                 /* If we have allocated from all of the OSTs, slowly
779                  * precess the next start if the OST/stripe count isn't
780                  * already doing this for us. */
781                 lqr->lqr_start_idx %= osts->op_count;
782                 if (stripe_count > 1 && (osts->op_count % stripe_count) != 1)
783                         ++lqr->lqr_offset_idx;
784         }
785         ost_start_idx_temp = lqr->lqr_start_idx;
786
787 repeat_find:
788
789         QOS_DEBUG("pool '%s' want %d start_idx %d start_count %d offset %d "
790                   "active %d count %d\n",
791                   lod_comp->llc_pool ? lod_comp->llc_pool : "",
792                   stripe_count, lqr->lqr_start_idx, lqr->lqr_start_count,
793                   lqr->lqr_offset_idx, osts->op_count, osts->op_count);
794
795         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
796                 stripes_per_ost =
797                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
798
799         for (i = 0; i < osts->op_count * stripes_per_ost
800              && stripe_idx < stripe_count; i++) {
801                 array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
802                                 osts->op_count;
803                 ++lqr->lqr_start_idx;
804                 ost_idx = lqr->lqr_pool.op_array[array_idx];
805
806                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
807                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
808                           stripe_idx, array_idx, ost_idx);
809
810                 if ((ost_idx == LOV_QOS_EMPTY) ||
811                     !cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
812                         continue;
813
814                 /* Fail Check before osc_precreate() is called
815                    so we can only 'fail' single OSC. */
816                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
817                         continue;
818
819                 spin_unlock(&lqr->lqr_alloc);
820                 rc = lod_check_and_reserve_ost(env, lo, lod_comp, ost_idx,
821                                                speed, &stripe_idx, stripe,
822                                                ost_indices, th, &overstriped);
823                 spin_lock(&lqr->lqr_alloc);
824
825                 if (rc != 0 && OST_TGT(m, ost_idx)->ltd_connecting)
826                         ost_connecting = 1;
827         }
828         if ((speed < 2) && (stripe_idx < stripe_count_min)) {
829                 /* Try again, allowing slower OSCs */
830                 speed++;
831                 lqr->lqr_start_idx = ost_start_idx_temp;
832
833                 ost_connecting = 0;
834                 goto repeat_find;
835         }
836
837         spin_unlock(&lqr->lqr_alloc);
838         up_read(&m->lod_ost_descs.ltd_qos.lq_rw_sem);
839
840         /* If there are enough OSTs, a component with overstriping requested
841          * will not actually end up overstriped.  The comp should reflect this.
842          */
843         if (!overstriped)
844                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
845
846         if (stripe_idx) {
847                 lod_comp->llc_stripe_count = stripe_idx;
848                 /* at least one stripe is allocated */
849                 rc = 0;
850         } else {
851                 /* nobody provided us with a single object */
852                 if (ost_connecting)
853                         rc = -EINPROGRESS;
854                 else
855                         rc = -ENOSPC;
856         }
857
858 out:
859         if (pool != NULL) {
860                 up_read(&pool_tgt_rw_sem(pool));
861                 /* put back ref got by lod_find_pool() */
862                 lod_pool_putref(pool);
863         }
864
865         RETURN(rc);
866 }
867
868 static int
869 lod_qos_mdt_in_use_init(const struct lu_env *env,
870                         const struct lu_tgt_descs *ltd,
871                         u32 stripe_idx, u32 stripe_count,
872                         const struct lu_tgt_pool *pool,
873                         struct dt_object **stripes)
874 {
875         u32 mdt_idx;
876         struct lu_tgt_desc *mdt;
877         int i, j;
878         int rc;
879
880         rc = lod_qos_tgt_in_use_clear(env, stripe_count);
881         if (rc)
882                 return rc;
883
884         /* if stripe_idx > 1, we are splitting directory, mark existing stripes
885          * in_use. Because for either split or creation, stripe 0 is local,
886          * don't mark it in use.
887          */
888         for (i = 1; i < stripe_idx; i++) {
889                 LASSERT(stripes[i]);
890                 for (j = 0; j < pool->op_count; j++) {
891                         mdt_idx = pool->op_array[j];
892
893                         if (!cfs_bitmap_check(ltd->ltd_tgt_bitmap, mdt_idx))
894                                 continue;
895
896                         mdt = LTD_TGT(ltd, mdt_idx);
897                         if (&mdt->ltd_tgt->dd_lu_dev ==
898                             stripes[i]->do_lu.lo_dev)
899                                 lod_qos_tgt_in_use(env, i, mdt_idx);
900                 }
901         }
902
903         return 0;
904 }
905
906 /**
907  * Allocate a striping using round-robin algorithm.
908  *
909  * Allocates a new striping using round-robin algorithm. The function refreshes
910  * all the internal structures (statfs cache, array of available remote MDTs
911  * sorted with regard to MDS, etc). The number of stripes required is taken from
912  * the object (must be prepared by the caller). The caller should ensure nobody
913  * else is trying to create a striping on the object in parallel. All the
914  * internal structures (like pools, etc) are protected and no additional locking
915  * is required. The function succeeds even if a single stripe is allocated.
916  *
917  * \param[in] env               execution environment for this thread
918  * \param[in] lo                LOD object
919  * \param[out] stripes          striping created
920  *
921  * \retval positive     stripe objects allocated, including the first stripe
922  *                      allocated outside
923  * \retval -ENOSPC      if not enough MDTs are found
924  * \retval negative     negated errno for other failures
925  */
926 int lod_mdt_alloc_rr(const struct lu_env *env, struct lod_object *lo,
927                      struct dt_object **stripes, u32 stripe_idx,
928                      u32 stripe_count)
929 {
930         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
931         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
932         struct lu_tgt_pool *pool;
933         struct lu_qos_rr *lqr;
934         struct lu_tgt_desc *mdt;
935         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
936         struct lu_fid fid = { 0 };
937         struct dt_object *dto;
938         unsigned int pool_idx;
939         unsigned int i;
940         u32 saved_idx = stripe_idx;
941         u32 start_mdt;
942         u32 mdt_idx;
943         bool use_degraded = false;
944         int tgt_connecting = 0;
945         int rc;
946
947         ENTRY;
948
949         pool = &ltd->ltd_tgt_pool;
950         lqr = &ltd->ltd_qos.lq_rr;
951         rc = lod_qos_calc_rr(lod, ltd, pool, lqr);
952         if (rc)
953                 RETURN(rc);
954
955         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
956                                      stripes);
957         if (rc)
958                 RETURN(rc);
959
960         down_read(&ltd->ltd_qos.lq_rw_sem);
961         spin_lock(&lqr->lqr_alloc);
962         if (--lqr->lqr_start_count <= 0) {
963                 lqr->lqr_start_idx = prandom_u32_max(pool->op_count);
964                 lqr->lqr_start_count =
965                         (LOV_CREATE_RESEED_MIN / max(pool->op_count, 1U) +
966                          LOV_CREATE_RESEED_MULT) * max(pool->op_count, 1U);
967         } else if (stripe_count - 1 >= pool->op_count ||
968                    lqr->lqr_start_idx > pool->op_count) {
969                 /* If we have allocated from all of the tgts, slowly
970                  * precess the next start if the tgt/stripe count isn't
971                  * already doing this for us. */
972                 lqr->lqr_start_idx %= pool->op_count;
973                 if (stripe_count - 1 > 1 &&
974                     (pool->op_count % (stripe_count - 1)) != 1)
975                         ++lqr->lqr_offset_idx;
976         }
977         start_mdt = lqr->lqr_start_idx;
978
979 repeat_find:
980         QOS_DEBUG("want=%d start_idx=%d start_count=%d offset=%d active=%d count=%d\n",
981                   stripe_count - 1, lqr->lqr_start_idx, lqr->lqr_start_count,
982                   lqr->lqr_offset_idx, pool->op_count, pool->op_count);
983
984         for (i = 0; i < pool->op_count && stripe_idx < stripe_count; i++) {
985                 pool_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
986                             pool->op_count;
987                 ++lqr->lqr_start_idx;
988                 mdt_idx = lqr->lqr_pool.op_array[pool_idx];
989                 mdt = LTD_TGT(ltd, mdt_idx);
990
991                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
992                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
993                           stripe_idx, pool_idx, mdt_idx);
994
995                 if (mdt_idx == LOV_QOS_EMPTY ||
996                     !cfs_bitmap_check(ltd->ltd_tgt_bitmap, mdt_idx))
997                         continue;
998
999                 /* do not put >1 objects on one MDT */
1000                 if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1001                         continue;
1002
1003                 rc = lod_is_tgt_usable(ltd, mdt);
1004                 if (rc) {
1005                         if (mdt->ltd_connecting)
1006                                 tgt_connecting = 1;
1007                         continue;
1008                 }
1009
1010                 /* try to use another OSP if this one is degraded */
1011                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED &&
1012                     !use_degraded) {
1013                         QOS_DEBUG("#%d: degraded\n", mdt_idx);
1014                         continue;
1015                 }
1016                 spin_unlock(&lqr->lqr_alloc);
1017
1018                 rc = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1019                 if (rc < 0) {
1020                         QOS_DEBUG("#%d: alloc FID failed: %dl\n", mdt_idx, rc);
1021                         spin_lock(&lqr->lqr_alloc);
1022                         continue;
1023                 }
1024
1025                 dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1026                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1027                                 &conf);
1028
1029                 spin_lock(&lqr->lqr_alloc);
1030                 if (IS_ERR(dto)) {
1031                         QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1032                                   mdt->ltd_index, (int) PTR_ERR(dto));
1033
1034                         if (mdt->ltd_connecting)
1035                                 tgt_connecting = 1;
1036                         continue;
1037                 }
1038
1039                 lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1040                 stripes[stripe_idx++] = dto;
1041         }
1042
1043         if (!use_degraded && stripe_idx < stripe_count) {
1044                 /* Try again, allowing slower MDTs */
1045                 use_degraded = true;
1046                 lqr->lqr_start_idx = start_mdt;
1047
1048                 tgt_connecting = 0;
1049                 goto repeat_find;
1050         }
1051         spin_unlock(&lqr->lqr_alloc);
1052         up_read(&ltd->ltd_qos.lq_rw_sem);
1053
1054         if (stripe_idx > saved_idx)
1055                 /* at least one stripe is allocated */
1056                 RETURN(stripe_idx);
1057
1058         /* nobody provided us with a single object */
1059         if (tgt_connecting)
1060                 RETURN(-EINPROGRESS);
1061
1062         RETURN(-ENOSPC);
1063 }
1064
1065 /**
1066  * Allocate a specific striping layout on a user defined set of OSTs.
1067  *
1068  * Allocates new striping using the OST index range provided by the data from
1069  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1070  * OSTs are not considered. The exact order of OSTs requested by the user
1071  * is respected as much as possible depending on OST status. The number of
1072  * stripes needed and stripe offset are taken from the object. If that number
1073  * can not be met, then the function returns a failure and then it's the
1074  * caller's responsibility to release the stripes allocated. All the internal
1075  * structures are protected, but no concurrent allocation is allowed on the
1076  * same objects.
1077  *
1078  * \param[in] env               execution environment for this thread
1079  * \param[in] lo                LOD object
1080  * \param[out] stripe           striping created
1081  * \param[out] ost_indices      ost indices of striping created
1082  * \param[in] th                transaction handle
1083  * \param[in] comp_idx          index of ldo_comp_entries
1084  *
1085  * \retval 0            on success
1086  * \retval -ENODEV      OST index does not exist on file system
1087  * \retval -EINVAL      requested OST index is invalid
1088  * \retval negative     negated errno on error
1089  */
1090 static int lod_alloc_ost_list(const struct lu_env *env, struct lod_object *lo,
1091                               struct dt_object **stripe, __u32 *ost_indices,
1092                               struct thandle *th, int comp_idx)
1093 {
1094         struct lod_layout_component *lod_comp;
1095         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1096         struct dt_object        *o;
1097         unsigned int            array_idx = 0;
1098         int                     stripe_count = 0;
1099         int                     i;
1100         int                     rc = -EINVAL;
1101         ENTRY;
1102
1103         /* for specific OSTs layout */
1104         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1105         lod_comp = &lo->ldo_comp_entries[comp_idx];
1106         LASSERT(lod_comp->llc_ostlist.op_array);
1107         LASSERT(lod_comp->llc_ostlist.op_count);
1108
1109         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1110         if (rc < 0)
1111                 RETURN(rc);
1112
1113         if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT)
1114                 lod_comp->llc_stripe_offset =
1115                                 lod_comp->llc_ostlist.op_array[0];
1116
1117         for (i = 0; i < lod_comp->llc_stripe_count; i++) {
1118                 if (lod_comp->llc_ostlist.op_array[i] ==
1119                     lod_comp->llc_stripe_offset) {
1120                         array_idx = i;
1121                         break;
1122                 }
1123         }
1124         if (i == lod_comp->llc_stripe_count) {
1125                 CDEBUG(D_OTHER,
1126                        "%s: start index %d not in the specified list of OSTs\n",
1127                        lod2obd(m)->obd_name, lod_comp->llc_stripe_offset);
1128                 RETURN(-EINVAL);
1129         }
1130
1131         for (i = 0; i < lod_comp->llc_stripe_count;
1132              i++, array_idx = (array_idx + 1) % lod_comp->llc_stripe_count) {
1133                 __u32 ost_idx = lod_comp->llc_ostlist.op_array[array_idx];
1134
1135                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx)) {
1136                         rc = -ENODEV;
1137                         break;
1138                 }
1139
1140                 /* do not put >1 objects on a single OST, except for
1141                  * overstriping
1142                  */
1143                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_count) &&
1144                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)) {
1145                         rc = -EINVAL;
1146                         break;
1147                 }
1148
1149                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs,
1150                                           LTD_TGT(&m->lod_ost_descs, ost_idx));
1151                 if (rc < 0) /* this OSP doesn't feel well */
1152                         break;
1153
1154                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1155                 if (IS_ERR(o)) {
1156                         rc = PTR_ERR(o);
1157                         CDEBUG(D_OTHER,
1158                                "%s: can't declare new object on #%u: %d\n",
1159                                lod2obd(m)->obd_name, ost_idx, rc);
1160                         break;
1161                 }
1162
1163                 /*
1164                  * We've successfully declared (reserved) an object
1165                  */
1166                 lod_qos_tgt_in_use(env, stripe_count, ost_idx);
1167                 stripe[stripe_count] = o;
1168                 ost_indices[stripe_count] = ost_idx;
1169                 stripe_count++;
1170         }
1171
1172         RETURN(rc);
1173 }
1174
1175 /**
1176  * Allocate a striping on a predefined set of OSTs.
1177  *
1178  * Allocates new layout starting from OST index in lo->ldo_stripe_offset.
1179  * Full OSTs are not considered. The exact order of OSTs is not important and
1180  * varies depending on OST status. The allocation procedure prefers the targets
1181  * with precreated objects ready. The number of stripes needed and stripe
1182  * offset are taken from the object. If that number cannot be met, then the
1183  * function returns an error and then it's the caller's responsibility to
1184  * release the stripes allocated. All the internal structures are protected,
1185  * but no concurrent allocation is allowed on the same objects.
1186  *
1187  * \param[in] env               execution environment for this thread
1188  * \param[in] lo                LOD object
1189  * \param[out] stripe           striping created
1190  * \param[out] ost_indices      ost indices of striping created
1191  * \param[in] flags             not used
1192  * \param[in] th                transaction handle
1193  * \param[in] comp_idx          index of ldo_comp_entries
1194  *
1195  * \retval 0            on success
1196  * \retval -ENOSPC      if no OST objects are available at all
1197  * \retval -EFBIG       if not enough OST objects are found
1198  * \retval -EINVAL      requested offset is invalid
1199  * \retval negative     errno on failure
1200  */
1201 static int lod_ost_alloc_specific(const struct lu_env *env,
1202                                   struct lod_object *lo,
1203                                   struct dt_object **stripe, __u32 *ost_indices,
1204                                   int flags, struct thandle *th, int comp_idx)
1205 {
1206         struct lod_layout_component *lod_comp;
1207         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1208         struct dt_object *o;
1209         struct lu_tgt_desc *tgt;
1210         __u32 ost_idx;
1211         unsigned int i, array_idx, ost_count;
1212         int rc, stripe_num = 0;
1213         int speed = 0;
1214         struct pool_desc *pool = NULL;
1215         struct lu_tgt_pool *osts;
1216         int stripes_per_ost = 1;
1217         bool overstriped = false;
1218         ENTRY;
1219
1220         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1221         lod_comp = &lo->ldo_comp_entries[comp_idx];
1222
1223         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1224         if (rc)
1225                 GOTO(out, rc);
1226
1227         if (lod_comp->llc_pool != NULL)
1228                 pool = lod_find_pool(m, lod_comp->llc_pool);
1229
1230         if (pool != NULL) {
1231                 down_read(&pool_tgt_rw_sem(pool));
1232                 osts = &(pool->pool_obds);
1233         } else {
1234                 osts = &m->lod_ost_descs.ltd_tgt_pool;
1235         }
1236
1237         ost_count = osts->op_count;
1238
1239 repeat_find:
1240         /* search loi_ost_idx in ost array */
1241         array_idx = 0;
1242         for (i = 0; i < ost_count; i++) {
1243                 if (osts->op_array[i] == lod_comp->llc_stripe_offset) {
1244                         array_idx = i;
1245                         break;
1246                 }
1247         }
1248         if (i == ost_count) {
1249                 CERROR("Start index %d not found in pool '%s'\n",
1250                        lod_comp->llc_stripe_offset,
1251                        lod_comp->llc_pool ? lod_comp->llc_pool : "");
1252                 GOTO(out, rc = -EINVAL);
1253         }
1254
1255         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1256                 stripes_per_ost =
1257                         (lod_comp->llc_stripe_count - 1)/ost_count + 1;
1258
1259         for (i = 0; i < ost_count * stripes_per_ost;
1260                         i++, array_idx = (array_idx + 1) % ost_count) {
1261                 ost_idx = osts->op_array[array_idx];
1262
1263                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1264                         continue;
1265
1266                 /* Fail Check before osc_precreate() is called
1267                    so we can only 'fail' single OSC. */
1268                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1269                         continue;
1270
1271                 /*
1272                  * do not put >1 objects on a single OST, except for
1273                  * overstriping, where it is intended
1274                  */
1275                 if (lod_qos_is_tgt_used(env, ost_idx, stripe_num)) {
1276                         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1277                                 overstriped = true;
1278                         else
1279                                 continue;
1280                 }
1281
1282                 /*
1283                  * try not allocate on the OST used by other component
1284                  */
1285                 if (speed == 0 && i != 0 &&
1286                     lod_comp_is_ost_used(env, lo, ost_idx))
1287                         continue;
1288
1289                 tgt = LTD_TGT(&m->lod_ost_descs, ost_idx);
1290
1291                 /* Drop slow OSCs if we can, but not for requested start idx.
1292                  *
1293                  * This means "if OSC is slow and it is not the requested
1294                  * start OST, then it can be skipped, otherwise skip it only
1295                  * if it is inactive/recovering/out-of-space." */
1296
1297                 rc = lod_statfs_and_check(env, m, &m->lod_ost_descs, tgt);
1298                 if (rc) {
1299                         /* this OSP doesn't feel well */
1300                         continue;
1301                 }
1302
1303                 /*
1304                  * We expect number of precreated objects at the first
1305                  * iteration.  Skip OSPs with no objects ready.  Don't apply
1306                  * this logic to OST specified with stripe_offset.
1307                  */
1308                 if (i && !tgt->ltd_statfs.os_fprecreated && !speed)
1309                         continue;
1310
1311                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1312                 if (IS_ERR(o)) {
1313                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1314                                ost_idx, (int) PTR_ERR(o));
1315                         continue;
1316                 }
1317
1318                 /*
1319                  * We've successfully declared (reserved) an object
1320                  */
1321                 lod_qos_tgt_in_use(env, stripe_num, ost_idx);
1322                 stripe[stripe_num] = o;
1323                 ost_indices[stripe_num] = ost_idx;
1324                 stripe_num++;
1325
1326                 /* We have enough stripes */
1327                 if (stripe_num == lod_comp->llc_stripe_count)
1328                         GOTO(out, rc = 0);
1329         }
1330         if (speed < 2) {
1331                 /* Try again, allowing slower OSCs */
1332                 speed++;
1333                 goto repeat_find;
1334         }
1335
1336         /* If we were passed specific striping params, then a failure to
1337          * meet those requirements is an error, since we can't reallocate
1338          * that memory (it might be part of a larger array or something).
1339          */
1340         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1341                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1342                lod_comp->llc_stripe_count);
1343         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1344
1345         /* If there are enough OSTs, a component with overstriping requessted
1346          * will not actually end up overstriped.  The comp should reflect this.
1347          */
1348         if (rc == 0 && !overstriped)
1349                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1350
1351 out:
1352         if (pool != NULL) {
1353                 up_read(&pool_tgt_rw_sem(pool));
1354                 /* put back ref got by lod_find_pool() */
1355                 lod_pool_putref(pool);
1356         }
1357
1358         RETURN(rc);
1359 }
1360
1361 /**
1362  * Allocate a striping using an algorithm with weights.
1363  *
1364  * The function allocates OST objects to create a striping. The algorithm
1365  * used is based on weights (currently only using the free space), and it's
1366  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1367  * configuration (# of stripes, offset, pool) is taken from the object and
1368  * is prepared by the caller.
1369  *
1370  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1371  * be met due to too few OSTs, then allocation fails. If the flag is passed
1372  * fewer than 3/4 of the requested number of stripes can be allocated, then
1373  * allocation fails.
1374  *
1375  * No concurrent allocation is allowed on the object and this must be ensured
1376  * by the caller. All the internal structures are protected by the function.
1377  *
1378  * The algorithm has two steps: find available OSTs and calculate their
1379  * weights, then select the OSTs with their weights used as the probability.
1380  * An OST with a higher weight is proportionately more likely to be selected
1381  * than one with a lower weight.
1382  *
1383  * \param[in] env               execution environment for this thread
1384  * \param[in] lo                LOD object
1385  * \param[out] stripe           striping created
1386  * \param[out] ost_indices      ost indices of striping created
1387  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
1388  * \param[in] th                transaction handle
1389  * \param[in] comp_idx          index of ldo_comp_entries
1390  *
1391  * \retval 0            on success
1392  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1393  * \retval -EINVAL      requested OST index is invalid
1394  * \retval negative     errno on failure
1395  */
1396 static int lod_ost_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1397                              struct dt_object **stripe, __u32 *ost_indices,
1398                              int flags, struct thandle *th, int comp_idx)
1399 {
1400         struct lod_layout_component *lod_comp;
1401         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1402         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
1403         struct lod_tgt_desc *ost;
1404         struct dt_object *o;
1405         __u64 total_weight = 0;
1406         struct pool_desc *pool = NULL;
1407         struct lu_tgt_pool *osts;
1408         unsigned int i;
1409         __u32 nfound, good_osts, stripe_count, stripe_count_min;
1410         bool overstriped = false;
1411         int stripes_per_ost = 1;
1412         int rc = 0;
1413         ENTRY;
1414
1415         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
1416         lod_comp = &lo->ldo_comp_entries[comp_idx];
1417         stripe_count = lod_comp->llc_stripe_count;
1418         stripe_count_min = min_stripe_count(stripe_count, flags);
1419         if (stripe_count_min < 1)
1420                 RETURN(-EINVAL);
1421
1422         if (lod_comp->llc_pool != NULL)
1423                 pool = lod_find_pool(lod, lod_comp->llc_pool);
1424
1425         if (pool != NULL) {
1426                 down_read(&pool_tgt_rw_sem(pool));
1427                 osts = &(pool->pool_obds);
1428         } else {
1429                 osts = &lod->lod_ost_descs.ltd_tgt_pool;
1430         }
1431
1432         /* Detect -EAGAIN early, before expensive lock is taken. */
1433         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1434                 GOTO(out_nolock, rc = -EAGAIN);
1435
1436         if (lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING)
1437                 stripes_per_ost =
1438                         (lod_comp->llc_stripe_count - 1)/osts->op_count + 1;
1439
1440         /* Do actual allocation, use write lock here. */
1441         down_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1442
1443         /*
1444          * Check again, while we were sleeping on @lq_rw_sem things could
1445          * change.
1446          */
1447         if (!ltd_qos_is_usable(&lod->lod_ost_descs))
1448                 GOTO(out, rc = -EAGAIN);
1449
1450         rc = ltd_qos_penalties_calc(&lod->lod_ost_descs);
1451         if (rc)
1452                 GOTO(out, rc);
1453
1454         rc = lod_qos_tgt_in_use_clear(env, lod_comp->llc_stripe_count);
1455         if (rc)
1456                 GOTO(out, rc);
1457
1458         good_osts = 0;
1459         /* Find all the OSTs that are valid stripe candidates */
1460         for (i = 0; i < osts->op_count; i++) {
1461                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, osts->op_array[i]))
1462                         continue;
1463
1464                 ost = OST_TGT(lod, osts->op_array[i]);
1465                 ost->ltd_qos.ltq_usable = 0;
1466
1467                 rc = lod_statfs_and_check(env, lod, &lod->lod_ost_descs, ost);
1468                 if (rc) {
1469                         /* this OSP doesn't feel well */
1470                         continue;
1471                 }
1472
1473                 if (ost->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1474                         continue;
1475
1476                 /* Fail Check before osc_precreate() is called
1477                  * so we can only 'fail' single OSC.
1478                  */
1479                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1480                                    osts->op_array[i] == 0)
1481                         continue;
1482
1483                 ost->ltd_qos.ltq_usable = 1;
1484                 lu_tgt_qos_weight_calc(ost);
1485                 total_weight += ost->ltd_qos.ltq_weight;
1486
1487                 good_osts++;
1488         }
1489
1490         QOS_DEBUG("found %d good osts\n", good_osts);
1491
1492         if (good_osts < stripe_count_min)
1493                 GOTO(out, rc = -EAGAIN);
1494
1495         /* If we do not have enough OSTs for the requested stripe count, do not
1496          * put more stripes per OST than requested.
1497          */
1498         if (stripe_count / stripes_per_ost > good_osts)
1499                 stripe_count = good_osts * stripes_per_ost;
1500
1501         /* Find enough OSTs with weighted random allocation. */
1502         nfound = 0;
1503         while (nfound < stripe_count) {
1504                 u64 rand, cur_weight;
1505
1506                 cur_weight = 0;
1507                 rc = -ENOSPC;
1508
1509                 rand = lu_prandom_u64_max(total_weight);
1510
1511                 /* On average, this will hit larger-weighted OSTs more often.
1512                  * 0-weight OSTs will always get used last (only when rand=0)
1513                  */
1514                 for (i = 0; i < osts->op_count; i++) {
1515                         __u32 idx = osts->op_array[i];
1516
1517                         if (lod_should_avoid_ost(lo, lag, idx))
1518                                 continue;
1519
1520                         ost = OST_TGT(lod, idx);
1521
1522                         if (!ost->ltd_qos.ltq_usable)
1523                                 continue;
1524
1525                         cur_weight += ost->ltd_qos.ltq_weight;
1526                         QOS_DEBUG("stripe_count=%d nfound=%d cur_weight=%llu "
1527                                   "rand=%llu total_weight=%llu\n",
1528                                   stripe_count, nfound, cur_weight, rand,
1529                                   total_weight);
1530
1531                         if (cur_weight < rand)
1532                                 continue;
1533
1534                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1535                         /*
1536                          * do not put >1 objects on a single OST, except for
1537                          * overstriping
1538                          */
1539                         if ((lod_comp_is_ost_used(env, lo, idx)) &&
1540                             !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
1541                                 continue;
1542
1543                         if (lod_qos_is_tgt_used(env, idx, nfound)) {
1544                                 if (lod_comp->llc_pattern &
1545                                     LOV_PATTERN_OVERSTRIPING)
1546                                         overstriped = true;
1547                                 else
1548                                         continue;
1549                         }
1550
1551                         o = lod_qos_declare_object_on(env, lod, idx, th);
1552                         if (IS_ERR(o)) {
1553                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1554                                           idx, (int) PTR_ERR(o));
1555                                 continue;
1556                         }
1557
1558                         lod_avoid_update(lo, lag);
1559                         lod_qos_tgt_in_use(env, nfound, idx);
1560                         stripe[nfound] = o;
1561                         ost_indices[nfound] = idx;
1562                         ltd_qos_update(&lod->lod_ost_descs, ost, &total_weight);
1563                         nfound++;
1564                         rc = 0;
1565                         break;
1566                 }
1567
1568                 if (rc) {
1569                         /* no OST found on this iteration, give up */
1570                         break;
1571                 }
1572         }
1573
1574         if (unlikely(nfound != stripe_count)) {
1575                 /*
1576                  * when the decision to use weighted algorithm was made
1577                  * we had enough appropriate OSPs, but this state can
1578                  * change anytime (no space on OST, broken connection, etc)
1579                  * so it's possible OSP won't be able to provide us with
1580                  * an object due to just changed state
1581                  */
1582                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1583                           lod2obd(lod)->obd_name, stripe_count, nfound);
1584                 for (i = 0; i < nfound; i++) {
1585                         LASSERT(stripe[i] != NULL);
1586                         dt_object_put(env, stripe[i]);
1587                         stripe[i] = NULL;
1588                 }
1589
1590                 /* makes sense to rebalance next time */
1591                 lod->lod_ost_descs.ltd_qos.lq_dirty = 1;
1592                 lod->lod_ost_descs.ltd_qos.lq_same_space = 0;
1593
1594                 rc = -EAGAIN;
1595         }
1596
1597         /* If there are enough OSTs, a component with overstriping requessted
1598          * will not actually end up overstriped.  The comp should reflect this.
1599          */
1600         if (rc == 0 && !overstriped)
1601                 lod_comp->llc_pattern &= ~LOV_PATTERN_OVERSTRIPING;
1602
1603 out:
1604         up_write(&lod->lod_ost_descs.ltd_qos.lq_rw_sem);
1605
1606 out_nolock:
1607         if (pool != NULL) {
1608                 up_read(&pool_tgt_rw_sem(pool));
1609                 /* put back ref got by lod_find_pool() */
1610                 lod_pool_putref(pool);
1611         }
1612
1613         RETURN(rc);
1614 }
1615
1616 /**
1617  * Allocate a striping using an algorithm with weights.
1618  *
1619  * The function allocates remote MDT objects to create a striping, the first
1620  * object was already allocated on current MDT to ensure master object and
1621  * the first object are on the same MDT. The algorithm used is based on weights
1622  * (both free space and inodes), and it's trying to ensure the space/inodes are
1623  * used evenly by MDTs and MDSs. The striping configuration (# of stripes,
1624  * offset, pool) is taken from the object and is prepared by the caller.
1625  *
1626  * If prepared configuration can't be met due to too few MDTs, then allocation
1627  * fails.
1628  *
1629  * No concurrent allocation is allowed on the object and this must be ensured
1630  * by the caller. All the internal structures are protected by the function.
1631  *
1632  * The algorithm has two steps: find available MDTs and calculate their
1633  * weights, then select the MDTs with their weights used as the probability.
1634  * An MDT with a higher weight is proportionately more likely to be selected
1635  * than one with a lower weight.
1636  *
1637  * \param[in] env               execution environment for this thread
1638  * \param[in] lo                LOD object
1639  * \param[in] stripe_idx        starting stripe index to allocate, if it's not
1640  *                              0, we are restriping directory
1641  * \param[in] stripe_count      total stripe count
1642  * \param[out] stripes          striping created
1643  *
1644  * \retval positive     stripes allocated, and it should be equal to
1645  *                      lo->ldo_dir_stripe_count
1646  * \retval -EAGAIN      not enough tgts are found for specified stripe count
1647  * \retval -EINVAL      requested MDT index is invalid
1648  * \retval negative     errno on failure
1649  */
1650 int lod_mdt_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1651                       struct dt_object **stripes, u32 stripe_idx,
1652                       u32 stripe_count)
1653 {
1654         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1655         struct lu_tgt_descs *ltd = &lod->lod_mdt_descs;
1656         struct lu_object_conf conf = { .loc_flags = LOC_F_NEW };
1657         struct lu_fid fid = { 0 };
1658         const struct lu_tgt_pool *pool;
1659         struct lu_tgt_desc *mdt;
1660         struct dt_object *dto;
1661         u64 total_weight = 0;
1662         u32 saved_idx = stripe_idx;
1663         u32 mdt_idx;
1664         unsigned int good_mdts;
1665         unsigned int i;
1666         int rc = 0;
1667
1668         ENTRY;
1669
1670         LASSERT(stripe_idx <= stripe_count);
1671         if (stripe_idx == stripe_count)
1672                 RETURN(stripe_count);
1673
1674         /* use MDT pool in @ltd, once MDT pool is supported in the future, it
1675          * can be passed in as argument like OST object allocation.
1676          */
1677         pool = &ltd->ltd_tgt_pool;
1678
1679         /* Detect -EAGAIN early, before expensive lock is taken. */
1680         if (!ltd_qos_is_usable(ltd))
1681                 RETURN(-EAGAIN);
1682
1683         rc = lod_qos_mdt_in_use_init(env, ltd, stripe_idx, stripe_count, pool,
1684                                      stripes);
1685         if (rc)
1686                 RETURN(rc);
1687
1688         /* Do actual allocation, use write lock here. */
1689         down_write(&ltd->ltd_qos.lq_rw_sem);
1690
1691         /*
1692          * Check again, while we were sleeping on @lq_rw_sem things could
1693          * change.
1694          */
1695         if (!ltd_qos_is_usable(ltd))
1696                 GOTO(unlock, rc = -EAGAIN);
1697
1698         rc = ltd_qos_penalties_calc(ltd);
1699         if (rc)
1700                 GOTO(unlock, rc);
1701
1702         good_mdts = 0;
1703         /* Find all the MDTs that are valid stripe candidates */
1704         for (i = 0; i < pool->op_count; i++) {
1705                 if (!cfs_bitmap_check(ltd->ltd_tgt_bitmap, pool->op_array[i]))
1706                         continue;
1707
1708                 mdt = LTD_TGT(ltd, pool->op_array[i]);
1709                 mdt->ltd_qos.ltq_usable = 0;
1710
1711                 rc = lod_is_tgt_usable(ltd, mdt);
1712                 if (rc)
1713                         continue;
1714
1715                 if (mdt->ltd_statfs.os_state & OS_STATFS_DEGRADED)
1716                         continue;
1717
1718                 mdt->ltd_qos.ltq_usable = 1;
1719                 lu_tgt_qos_weight_calc(mdt);
1720                 total_weight += mdt->ltd_qos.ltq_weight;
1721
1722                 good_mdts++;
1723         }
1724
1725         QOS_DEBUG("found %d good MDTs\n", good_mdts);
1726
1727         if (good_mdts < stripe_count - stripe_idx)
1728                 GOTO(unlock, rc = -EAGAIN);
1729
1730         /* Find enough MDTs with weighted random allocation. */
1731         while (stripe_idx < stripe_count) {
1732                 u64 rand, cur_weight;
1733
1734                 cur_weight = 0;
1735                 rc = -ENOSPC;
1736
1737                 rand = lu_prandom_u64_max(total_weight);
1738
1739                 /* On average, this will hit larger-weighted MDTs more often.
1740                  * 0-weight MDT will always get used last (only when rand=0) */
1741                 for (i = 0; i < pool->op_count; i++) {
1742                         int rc2;
1743
1744                         mdt_idx = pool->op_array[i];
1745                         mdt = LTD_TGT(ltd, mdt_idx);
1746
1747                         if (!mdt->ltd_qos.ltq_usable)
1748                                 continue;
1749
1750                         cur_weight += mdt->ltd_qos.ltq_weight;
1751
1752                         QOS_DEBUG("stripe_count=%d stripe_index=%d cur_weight=%llu rand=%llu total_weight=%llu\n",
1753                                   stripe_count, stripe_idx, cur_weight, rand,
1754                                   total_weight);
1755
1756                         if (cur_weight < rand)
1757                                 continue;
1758
1759                         QOS_DEBUG("stripe=%d to idx=%d\n",
1760                                   stripe_idx, mdt_idx);
1761
1762                         if (lod_qos_is_tgt_used(env, mdt_idx, stripe_idx))
1763                                 continue;
1764
1765                         rc2 = dt_fid_alloc(env, mdt->ltd_tgt, &fid, NULL, NULL);
1766                         if (rc2 < 0) {
1767                                 QOS_DEBUG("can't alloc FID on #%u: %d\n",
1768                                           mdt_idx, rc2);
1769                                 continue;
1770                         }
1771
1772                         conf.loc_flags = LOC_F_NEW;
1773                         dto = dt_locate_at(env, mdt->ltd_tgt, &fid,
1774                                 lo->ldo_obj.do_lu.lo_dev->ld_site->ls_top_dev,
1775                                 &conf);
1776                         if (IS_ERR(dto)) {
1777                                 QOS_DEBUG("can't alloc stripe on #%u: %d\n",
1778                                           mdt_idx, (int) PTR_ERR(dto));
1779                                 continue;
1780                         }
1781
1782                         lod_qos_tgt_in_use(env, stripe_idx, mdt_idx);
1783                         stripes[stripe_idx] = dto;
1784                         ltd_qos_update(ltd, mdt, &total_weight);
1785                         stripe_idx++;
1786                         rc = 0;
1787                         break;
1788                 }
1789
1790                 /* no MDT found on this iteration, give up */
1791                 if (rc)
1792                         break;
1793         }
1794
1795         if (unlikely(stripe_idx != stripe_count)) {
1796                 /*
1797                  * when the decision to use weighted algorithm was made
1798                  * we had enough appropriate OSPs, but this state can
1799                  * change anytime (no space on MDT, broken connection, etc)
1800                  * so it's possible OSP won't be able to provide us with
1801                  * an object due to just changed state
1802                  */
1803                 QOS_DEBUG("%s: wanted %d objects, found only %d\n",
1804                           lod2obd(lod)->obd_name, stripe_count, stripe_idx);
1805                 for (i = saved_idx; i < stripe_idx; i++) {
1806                         LASSERT(stripes[i] != NULL);
1807                         dt_object_put(env, stripes[i]);
1808                         stripes[i] = NULL;
1809                 }
1810
1811                 /* makes sense to rebalance next time */
1812                 ltd->ltd_qos.lq_dirty = 1;
1813                 ltd->ltd_qos.lq_same_space = 0;
1814
1815                 rc = -EAGAIN;
1816         } else {
1817                 rc = stripe_idx;
1818         }
1819
1820 unlock:
1821         up_write(&ltd->ltd_qos.lq_rw_sem);
1822
1823         RETURN(rc);
1824 }
1825
1826 /**
1827  * Check stripe count the caller can use.
1828  *
1829  * For new layouts (no initialized components), check the total size of the
1830  * layout against the maximum EA size from the backing file system.  This
1831  * stops us from creating a layout which will be too large once initialized.
1832  *
1833  * For existing layouts (with initialized components):
1834  * Find the maximal possible stripe count not greater than \a stripe_count.
1835  * If the provided stripe count is 0, then the filesystem's default is used.
1836  *
1837  * \param[in] lod       LOD device
1838  * \param[in] lo        The lod_object
1839  * \param[in] stripe_count      count the caller would like to use
1840  *
1841  * \retval              the maximum usable stripe count
1842  */
1843 __u16 lod_get_stripe_count(struct lod_device *lod, struct lod_object *lo,
1844                            __u16 stripe_count, bool overstriping)
1845 {
1846         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1847         /* max stripe count is based on OSD ea size */
1848         unsigned int easize = lod->lod_osd_max_easize;
1849         int i;
1850
1851
1852         if (!stripe_count)
1853                 stripe_count =
1854                         lod->lod_ost_descs.ltd_lov_desc.ld_default_stripe_count;
1855         if (!stripe_count)
1856                 stripe_count = 1;
1857         /* Overstriping allows more stripes than targets */
1858         if (stripe_count >
1859                 lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count &&
1860             !overstriping)
1861                 stripe_count =
1862                         lod->lod_ost_descs.ltd_lov_desc.ld_active_tgt_count;
1863
1864         if (lo->ldo_is_composite) {
1865                 struct lod_layout_component *lod_comp;
1866                 unsigned int header_sz = sizeof(struct lov_comp_md_v1);
1867                 unsigned int init_comp_sz = 0;
1868                 unsigned int total_comp_sz = 0;
1869                 unsigned int comp_sz;
1870
1871                 header_sz += sizeof(struct lov_comp_md_entry_v1) *
1872                                 lo->ldo_comp_cnt;
1873
1874                 for (i = 0; i < lo->ldo_comp_cnt; i++) {
1875                         lod_comp = &lo->ldo_comp_entries[i];
1876                         comp_sz = lov_mds_md_size(lod_comp->llc_stripe_count,
1877                                                   LOV_MAGIC_V3);
1878                         total_comp_sz += comp_sz;
1879                         if (lod_comp->llc_flags & LCME_FL_INIT)
1880                                 init_comp_sz += comp_sz;
1881                 }
1882
1883                 if (init_comp_sz > 0)
1884                         total_comp_sz = init_comp_sz;
1885
1886                 header_sz += total_comp_sz;
1887
1888                 if (easize > header_sz)
1889                         easize -= header_sz;
1890                 else
1891                         easize = 0;
1892         }
1893
1894         max_stripes = lov_mds_md_max_stripe_count(easize, LOV_MAGIC_V3);
1895         max_stripes = (max_stripes == 0) ? 0 : max_stripes - 1;
1896
1897         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1898 }
1899
1900 /**
1901  * Create in-core respresentation for a fully-defined striping
1902  *
1903  * When the caller passes a fully-defined striping (i.e. everything including
1904  * OST object FIDs are defined), then we still need to instantiate LU-cache
1905  * with the objects representing the stripes defined. This function completes
1906  * that task.
1907  *
1908  * \param[in] env       execution environment for this thread
1909  * \param[in] mo        LOD object
1910  * \param[in] buf       buffer containing the striping
1911  *
1912  * \retval 0            on success
1913  * \retval negative     negated errno on error
1914  */
1915 int lod_use_defined_striping(const struct lu_env *env,
1916                              struct lod_object *mo,
1917                              const struct lu_buf *buf)
1918 {
1919         struct lod_layout_component *lod_comp;
1920         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1921         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1922         struct lov_comp_md_v1  *comp_v1 = NULL;
1923         struct lov_ost_data_v1 *objs;
1924         __u32   magic;
1925         __u16   comp_cnt;
1926         __u16   mirror_cnt;
1927         int     rc = 0, i;
1928         ENTRY;
1929
1930         mutex_lock(&mo->ldo_layout_mutex);
1931         lod_striping_free_nolock(env, mo);
1932
1933         magic = le32_to_cpu(v1->lmm_magic) & ~LOV_MAGIC_DEFINED;
1934
1935         if (magic != LOV_MAGIC_V1 && magic != LOV_MAGIC_V3 &&
1936             magic != LOV_MAGIC_COMP_V1 && magic != LOV_MAGIC_FOREIGN)
1937                 GOTO(unlock, rc = -EINVAL);
1938
1939         if (magic == LOV_MAGIC_COMP_V1) {
1940                 comp_v1 = buf->lb_buf;
1941                 comp_cnt = le16_to_cpu(comp_v1->lcm_entry_count);
1942                 if (comp_cnt == 0)
1943                         GOTO(unlock, rc = -EINVAL);
1944                 mirror_cnt = le16_to_cpu(comp_v1->lcm_mirror_count) + 1;
1945                 mo->ldo_flr_state = le16_to_cpu(comp_v1->lcm_flags) &
1946                                         LCM_FL_FLR_MASK;
1947                 mo->ldo_is_composite = 1;
1948         } else if (magic == LOV_MAGIC_FOREIGN) {
1949                 struct lov_foreign_md *foreign;
1950                 size_t length;
1951
1952                 if (buf->lb_len < offsetof(typeof(*foreign), lfm_value)) {
1953                         CDEBUG(D_LAYOUT,
1954                                "buf len %zu < min lov_foreign_md size (%zu)\n",
1955                                buf->lb_len,
1956                                offsetof(typeof(*foreign), lfm_value));
1957                         GOTO(out, rc = -EINVAL);
1958                 }
1959                 foreign = (struct lov_foreign_md *)buf->lb_buf;
1960                 length = foreign_size_le(foreign);
1961                 if (buf->lb_len < length) {
1962                         CDEBUG(D_LAYOUT,
1963                                "buf len %zu < this lov_foreign_md size (%zu)\n",
1964                                buf->lb_len, length);
1965                         GOTO(out, rc = -EINVAL);
1966                 }
1967
1968                 /* just cache foreign LOV EA raw */
1969                 rc = lod_alloc_foreign_lov(mo, length);
1970                 if (rc)
1971                         GOTO(out, rc);
1972                 memcpy(mo->ldo_foreign_lov, buf->lb_buf, length);
1973                 GOTO(out, rc);
1974         } else {
1975                 mo->ldo_is_composite = 0;
1976                 comp_cnt = 1;
1977                 mirror_cnt = 0;
1978         }
1979         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1980
1981         rc = lod_alloc_comp_entries(mo, mirror_cnt, comp_cnt);
1982         if (rc)
1983                 GOTO(unlock, rc);
1984
1985         for (i = 0; i < comp_cnt; i++) {
1986                 struct lu_extent *ext;
1987                 char    *pool_name;
1988                 __u32   offs;
1989
1990                 lod_comp = &mo->ldo_comp_entries[i];
1991
1992                 if (mo->ldo_is_composite) {
1993                         offs = le32_to_cpu(comp_v1->lcm_entries[i].lcme_offset);
1994                         v1 = (struct lov_mds_md_v1 *)((char *)comp_v1 + offs);
1995                         v3 = (struct lov_mds_md_v3 *)v1;
1996                         magic = le32_to_cpu(v1->lmm_magic);
1997
1998                         ext = &comp_v1->lcm_entries[i].lcme_extent;
1999                         lod_comp->llc_extent.e_start =
2000                                 le64_to_cpu(ext->e_start);
2001                         lod_comp->llc_extent.e_end = le64_to_cpu(ext->e_end);
2002                         lod_comp->llc_flags =
2003                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_flags);
2004                         if (lod_comp->llc_flags & LCME_FL_NOSYNC)
2005                                 lod_comp->llc_timestamp = le64_to_cpu(
2006                                         comp_v1->lcm_entries[i].lcme_timestamp);
2007                         lod_comp->llc_id =
2008                                 le32_to_cpu(comp_v1->lcm_entries[i].lcme_id);
2009                         if (lod_comp->llc_id == LCME_ID_INVAL)
2010                                 GOTO(out, rc = -EINVAL);
2011                 }
2012
2013                 pool_name = NULL;
2014                 if (magic == LOV_MAGIC_V1) {
2015                         objs = &v1->lmm_objects[0];
2016                 } else if (magic == LOV_MAGIC_V3) {
2017                         objs = &v3->lmm_objects[0];
2018                         if (v3->lmm_pool_name[0] != '\0')
2019                                 pool_name = v3->lmm_pool_name;
2020                 } else {
2021                         CDEBUG(D_LAYOUT, "Invalid magic %x\n", magic);
2022                         GOTO(out, rc = -EINVAL);
2023                 }
2024
2025                 lod_comp->llc_pattern = le32_to_cpu(v1->lmm_pattern);
2026                 lod_comp->llc_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
2027                 lod_comp->llc_stripe_count = le16_to_cpu(v1->lmm_stripe_count);
2028                 lod_comp->llc_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
2029                 /**
2030                  * The stripe_offset of an uninit-ed component is stored in
2031                  * the lmm_layout_gen
2032                  */
2033                 if (mo->ldo_is_composite && !lod_comp_inited(lod_comp))
2034                         lod_comp->llc_stripe_offset = lod_comp->llc_layout_gen;
2035                 lod_obj_set_pool(mo, i, pool_name);
2036
2037                 if ((!mo->ldo_is_composite || lod_comp_inited(lod_comp)) &&
2038                     !(lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED) &&
2039                     !(lod_comp->llc_pattern & LOV_PATTERN_MDT)) {
2040                         rc = lod_initialize_objects(env, mo, objs, i);
2041                         if (rc)
2042                                 GOTO(out, rc);
2043                 }
2044         }
2045
2046         rc = lod_fill_mirrors(mo);
2047         GOTO(out, rc);
2048 out:
2049         if (rc)
2050                 lod_striping_free_nolock(env, mo);
2051 unlock:
2052         mutex_unlock(&mo->ldo_layout_mutex);
2053
2054         RETURN(rc);
2055 }
2056
2057 /**
2058  * Parse suggested striping configuration.
2059  *
2060  * The caller gets a suggested striping configuration from a number of sources
2061  * including per-directory default and applications. Then it needs to verify
2062  * the suggested striping is valid, apply missing bits and store the resulting
2063  * configuration in the object to be used by the allocator later. Must not be
2064  * called concurrently against the same object. It's OK to provide a
2065  * fully-defined striping.
2066  *
2067  * \param[in] env       execution environment for this thread
2068  * \param[in] lo        LOD object
2069  * \param[in] buf       buffer containing the striping
2070  *
2071  * \retval 0            on success
2072  * \retval negative     negated errno on error
2073  */
2074 int lod_qos_parse_config(const struct lu_env *env, struct lod_object *lo,
2075                          const struct lu_buf *buf)
2076 {
2077         struct lod_layout_component *lod_comp;
2078         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2079         struct lov_desc *desc = &d->lod_ost_descs.ltd_lov_desc;
2080         struct lov_user_md_v1 *v1 = NULL;
2081         struct lov_user_md_v3 *v3 = NULL;
2082         struct lov_comp_md_v1 *comp_v1 = NULL;
2083         struct lov_foreign_md *lfm = NULL;
2084         char def_pool[LOV_MAXPOOLNAME + 1];
2085         __u32 magic;
2086         __u16 comp_cnt;
2087         __u16 mirror_cnt;
2088         int i, rc;
2089         ENTRY;
2090
2091         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
2092                 RETURN(0);
2093
2094         memset(def_pool, 0, sizeof(def_pool));
2095         if (lo->ldo_comp_entries != NULL)
2096                 lod_layout_get_pool(lo->ldo_comp_entries, lo->ldo_comp_cnt,
2097                                     def_pool, sizeof(def_pool));
2098
2099         /* free default striping info */
2100         if (lo->ldo_is_foreign)
2101                 lod_free_foreign_lov(lo);
2102         else
2103                 lod_free_comp_entries(lo);
2104
2105         rc = lod_verify_striping(env, d, lo, buf, false);
2106         if (rc)
2107                 RETURN(-EINVAL);
2108
2109         v3 = buf->lb_buf;
2110         v1 = buf->lb_buf;
2111         comp_v1 = buf->lb_buf;
2112         /* {lmm,lfm}_magic position/length work for all LOV formats */
2113         magic = v1->lmm_magic;
2114
2115         if (unlikely(le32_to_cpu(magic) & LOV_MAGIC_DEFINED)) {
2116                 /* try to use as fully defined striping */
2117                 rc = lod_use_defined_striping(env, lo, buf);
2118                 RETURN(rc);
2119         }
2120
2121         switch (magic) {
2122         case __swab32(LOV_USER_MAGIC_V1):
2123                 lustre_swab_lov_user_md_v1(v1);
2124                 magic = v1->lmm_magic;
2125                 /* fall through */
2126         case LOV_USER_MAGIC_V1:
2127                 break;
2128         case __swab32(LOV_USER_MAGIC_V3):
2129                 lustre_swab_lov_user_md_v3(v3);
2130                 magic = v3->lmm_magic;
2131                 /* fall through */
2132         case LOV_USER_MAGIC_V3:
2133                 break;
2134         case __swab32(LOV_USER_MAGIC_SPECIFIC):
2135                 lustre_swab_lov_user_md_v3(v3);
2136                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
2137                                                 v3->lmm_stripe_count);
2138                 magic = v3->lmm_magic;
2139                 /* fall through */
2140         case LOV_USER_MAGIC_SPECIFIC:
2141                 break;
2142         case __swab32(LOV_USER_MAGIC_COMP_V1):
2143                 lustre_swab_lov_comp_md_v1(comp_v1);
2144                 magic = comp_v1->lcm_magic;
2145                 /* fall trhough */
2146         case LOV_USER_MAGIC_COMP_V1:
2147                 break;
2148         case __swab32(LOV_USER_MAGIC_FOREIGN):
2149                 lfm = buf->lb_buf;
2150                 __swab32s(&lfm->lfm_magic);
2151                 __swab32s(&lfm->lfm_length);
2152                 __swab32s(&lfm->lfm_type);
2153                 __swab32s(&lfm->lfm_flags);
2154                 magic = lfm->lfm_magic;
2155                 /* fall through */
2156         case LOV_USER_MAGIC_FOREIGN:
2157                 if (!lfm)
2158                         lfm = buf->lb_buf;
2159                 rc = lod_alloc_foreign_lov(lo, foreign_size(lfm));
2160                 if (rc)
2161                         RETURN(rc);
2162                 memcpy(lo->ldo_foreign_lov, buf->lb_buf, foreign_size(lfm));
2163                 RETURN(0);
2164         default:
2165                 CERROR("%s: unrecognized magic %X\n",
2166                        lod2obd(d)->obd_name, magic);
2167                 RETURN(-EINVAL);
2168         }
2169
2170         lustre_print_user_md(D_OTHER, v1, "parse config");
2171
2172         if (magic == LOV_USER_MAGIC_COMP_V1) {
2173                 comp_cnt = comp_v1->lcm_entry_count;
2174                 if (comp_cnt == 0)
2175                         RETURN(-EINVAL);
2176                 mirror_cnt =  comp_v1->lcm_mirror_count + 1;
2177                 if (mirror_cnt > 1)
2178                         lo->ldo_flr_state = LCM_FL_RDONLY;
2179                 lo->ldo_is_composite = 1;
2180         } else {
2181                 comp_cnt = 1;
2182                 mirror_cnt = 0;
2183                 lo->ldo_is_composite = 0;
2184         }
2185
2186         rc = lod_alloc_comp_entries(lo, mirror_cnt, comp_cnt);
2187         if (rc)
2188                 RETURN(rc);
2189
2190         LASSERT(lo->ldo_comp_entries);
2191
2192         for (i = 0; i < comp_cnt; i++) {
2193                 struct pool_desc        *pool;
2194                 struct lu_extent        *ext;
2195                 char    *pool_name;
2196
2197                 lod_comp = &lo->ldo_comp_entries[i];
2198
2199                 if (lo->ldo_is_composite) {
2200                         v1 = (struct lov_user_md *)((char *)comp_v1 +
2201                                         comp_v1->lcm_entries[i].lcme_offset);
2202                         ext = &comp_v1->lcm_entries[i].lcme_extent;
2203                         lod_comp->llc_extent = *ext;
2204                         lod_comp->llc_flags =
2205                                 comp_v1->lcm_entries[i].lcme_flags &
2206                                         LCME_CL_COMP_FLAGS;
2207                 }
2208
2209                 pool_name = NULL;
2210                 if (v1->lmm_magic == LOV_USER_MAGIC_V3 ||
2211                     v1->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2212                         v3 = (struct lov_user_md_v3 *)v1;
2213                         if (v3->lmm_pool_name[0] != '\0')
2214                                 pool_name = v3->lmm_pool_name;
2215
2216                         if (v3->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
2217                                 rc = lod_comp_copy_ost_lists(lod_comp, v3);
2218                                 if (rc)
2219                                         GOTO(free_comp, rc);
2220                         }
2221                 }
2222
2223                 if (pool_name == NULL && def_pool[0] != '\0')
2224                         pool_name = def_pool;
2225
2226                 if (v1->lmm_pattern == 0)
2227                         v1->lmm_pattern = LOV_PATTERN_RAID0;
2228                 if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0 &&
2229                     lov_pattern(v1->lmm_pattern) != LOV_PATTERN_MDT &&
2230                     lov_pattern(v1->lmm_pattern) !=
2231                         (LOV_PATTERN_RAID0 | LOV_PATTERN_OVERSTRIPING)) {
2232                         CDEBUG(D_LAYOUT, "%s: invalid pattern: %x\n",
2233                                lod2obd(d)->obd_name, v1->lmm_pattern);
2234                         GOTO(free_comp, rc = -EINVAL);
2235                 }
2236
2237                 lod_comp->llc_pattern = v1->lmm_pattern;
2238                 lod_comp->llc_stripe_size = v1->lmm_stripe_size;
2239                 lod_adjust_stripe_size(lod_comp, desc->ld_default_stripe_size);
2240
2241                 lod_comp->llc_stripe_count = desc->ld_default_stripe_count;
2242                 if (v1->lmm_stripe_count ||
2243                     lov_pattern(v1->lmm_pattern) == LOV_PATTERN_MDT)
2244                         lod_comp->llc_stripe_count = v1->lmm_stripe_count;
2245
2246                 if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT &&
2247                     lod_comp->llc_stripe_count != 0) {
2248                         CDEBUG(D_LAYOUT, "%s: invalid stripe count: %u\n",
2249                                lod2obd(d)->obd_name,
2250                                lod_comp->llc_stripe_count);
2251                         GOTO(free_comp, rc = -EINVAL);
2252                 }
2253
2254                 lod_comp->llc_stripe_offset = v1->lmm_stripe_offset;
2255                 lod_obj_set_pool(lo, i, pool_name);
2256
2257                 if (pool_name == NULL)
2258                         continue;
2259
2260                 /* In the function below, .hs_keycmp resolves to
2261                  * pool_hashkey_keycmp() */
2262                 /* coverity[overrun-buffer-val] */
2263                 pool = lod_find_pool(d, pool_name);
2264                 if (pool == NULL)
2265                         continue;
2266
2267                 if (lod_comp->llc_stripe_offset != LOV_OFFSET_DEFAULT) {
2268                         rc = lod_check_index_in_pool(
2269                                         lod_comp->llc_stripe_offset, pool);
2270                         if (rc < 0) {
2271                                 lod_pool_putref(pool);
2272                                 CDEBUG(D_LAYOUT, "%s: invalid offset, %u\n",
2273                                        lod2obd(d)->obd_name,
2274                                        lod_comp->llc_stripe_offset);
2275                                 GOTO(free_comp, rc = -EINVAL);
2276                         }
2277                 }
2278
2279                 if (lod_comp->llc_stripe_count > pool_tgt_count(pool) &&
2280                     !(lod_comp->llc_pattern & LOV_PATTERN_OVERSTRIPING))
2281                         lod_comp->llc_stripe_count = pool_tgt_count(pool);
2282
2283                 lod_pool_putref(pool);
2284         }
2285
2286         RETURN(0);
2287
2288 free_comp:
2289         lod_free_comp_entries(lo);
2290         RETURN(rc);
2291 }
2292
2293 /**
2294  * prepare enough OST avoidance bitmap space
2295  */
2296 int lod_prepare_avoidance(const struct lu_env *env, struct lod_object *lo)
2297 {
2298         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2299         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2300         struct cfs_bitmap *bitmap = NULL;
2301         __u32 *new_oss = NULL;
2302
2303         lag->lag_ost_avail = lod->lod_ost_count;
2304
2305         /* reset OSS avoid guide array */
2306         lag->lag_oaa_count = 0;
2307         if (lag->lag_oss_avoid_array &&
2308             lag->lag_oaa_size < lod->lod_ost_count) {
2309                 OBD_FREE_PTR_ARRAY(lag->lag_oss_avoid_array, lag->lag_oaa_size);
2310                 lag->lag_oss_avoid_array = NULL;
2311                 lag->lag_oaa_size = 0;
2312         }
2313
2314         /* init OST avoid guide bitmap */
2315         if (lag->lag_ost_avoid_bitmap) {
2316                 if (lod->lod_ost_count <= lag->lag_ost_avoid_bitmap->size) {
2317                         CFS_RESET_BITMAP(lag->lag_ost_avoid_bitmap);
2318                 } else {
2319                         CFS_FREE_BITMAP(lag->lag_ost_avoid_bitmap);
2320                         lag->lag_ost_avoid_bitmap = NULL;
2321                 }
2322         }
2323
2324         if (!lag->lag_ost_avoid_bitmap) {
2325                 bitmap = CFS_ALLOCATE_BITMAP(lod->lod_ost_count);
2326                 if (!bitmap)
2327                         return -ENOMEM;
2328         }
2329
2330         if (!lag->lag_oss_avoid_array) {
2331                 /**
2332                  * usually there are multiple OSTs in one OSS, but we don't
2333                  * know the exact OSS number, so we choose a safe option,
2334                  * using OST count to allocate the array to store the OSS
2335                  * id.
2336                  */
2337                 OBD_ALLOC_PTR_ARRAY(new_oss, lod->lod_ost_count);
2338                 if (!new_oss) {
2339                         CFS_FREE_BITMAP(bitmap);
2340                         return -ENOMEM;
2341                 }
2342         }
2343
2344         if (new_oss) {
2345                 lag->lag_oss_avoid_array = new_oss;
2346                 lag->lag_oaa_size = lod->lod_ost_count;
2347         }
2348         if (bitmap)
2349                 lag->lag_ost_avoid_bitmap = bitmap;
2350
2351         return 0;
2352 }
2353
2354 /**
2355  * Collect information of used OSTs and OSSs in the overlapped components
2356  * of other mirrors
2357  */
2358 void lod_collect_avoidance(struct lod_object *lo, struct lod_avoid_guide *lag,
2359                            int comp_idx)
2360 {
2361         struct lod_device *lod = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
2362         struct lod_layout_component *lod_comp = &lo->ldo_comp_entries[comp_idx];
2363         struct cfs_bitmap *bitmap = lag->lag_ost_avoid_bitmap;
2364         int i, j;
2365
2366         /* iterate mirrors */
2367         for (i = 0; i < lo->ldo_mirror_count; i++) {
2368                 struct lod_layout_component *comp;
2369
2370                 /**
2371                  * skip mirror containing component[comp_idx], we only
2372                  * collect OSTs info of conflicting component in other mirrors,
2373                  * so that during read, if OSTs of a mirror's component are
2374                  * not available, we still have other mirror with different
2375                  * OSTs to read the data.
2376                  */
2377                 comp = &lo->ldo_comp_entries[lo->ldo_mirrors[i].lme_start];
2378                 if (comp->llc_id != LCME_ID_INVAL &&
2379                     mirror_id_of(comp->llc_id) ==
2380                                                 mirror_id_of(lod_comp->llc_id))
2381                         continue;
2382
2383                 /* iterate components of a mirror */
2384                 lod_foreach_mirror_comp(comp, lo, i) {
2385                         /**
2386                          * skip non-overlapped or un-instantiated components,
2387                          * NOTE: don't use lod_comp_inited(comp) to judge
2388                          * whether @comp has been inited, since during
2389                          * declare phase, comp->llc_stripe has been allocated
2390                          * while it's init flag not been set until the exec
2391                          * phase.
2392                          */
2393                         if (!lu_extent_is_overlapped(&comp->llc_extent,
2394                                                      &lod_comp->llc_extent) ||
2395                             !comp->llc_stripe)
2396                                 continue;
2397
2398                         /**
2399                          * collect used OSTs index and OSS info from a
2400                          * component
2401                          */
2402                         for (j = 0; j < comp->llc_stripe_count; j++) {
2403                                 struct lod_tgt_desc *ost;
2404                                 struct lu_svr_qos *lsq;
2405                                 int k;
2406
2407                                 ost = OST_TGT(lod, comp->llc_ost_indices[j]);
2408                                 lsq = ost->ltd_qos.ltq_svr;
2409
2410                                 if (cfs_bitmap_check(bitmap, ost->ltd_index))
2411                                         continue;
2412
2413                                 QOS_DEBUG("OST%d used in conflicting mirror "
2414                                           "component\n", ost->ltd_index);
2415                                 cfs_bitmap_set(bitmap, ost->ltd_index);
2416                                 lag->lag_ost_avail--;
2417
2418                                 for (k = 0; k < lag->lag_oaa_count; k++) {
2419                                         if (lag->lag_oss_avoid_array[k] ==
2420                                             lsq->lsq_id)
2421                                                 break;
2422                                 }
2423                                 if (k == lag->lag_oaa_count) {
2424                                         lag->lag_oss_avoid_array[k] =
2425                                                                 lsq->lsq_id;
2426                                         lag->lag_oaa_count++;
2427                                 }
2428                         }
2429                 }
2430         }
2431 }
2432
2433 /**
2434  * Create a striping for an obejct.
2435  *
2436  * The function creates a new striping for the object. The function tries QoS
2437  * algorithm first unless free space is distributed evenly among OSTs, but
2438  * by default RR algorithm is preferred due to internal concurrency (QoS is
2439  * serialized). The caller must ensure no concurrent calls to the function
2440  * are made against the same object.
2441  *
2442  * \param[in] env       execution environment for this thread
2443  * \param[in] lo        LOD object
2444  * \param[in] attr      attributes OST objects will be declared with
2445  * \param[in] th        transaction handle
2446  * \param[in] comp_idx  index of ldo_comp_entries
2447  *
2448  * \retval 0            on success
2449  * \retval negative     negated errno on error
2450  */
2451 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
2452                         struct lu_attr *attr, struct thandle *th,
2453                         int comp_idx)
2454 {
2455         struct lod_layout_component *lod_comp;
2456         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2457         int                     stripe_len;
2458         int                     flag = LOV_USES_ASSIGNED_STRIPE;
2459         int                     i, rc = 0;
2460         struct lod_avoid_guide *lag = &lod_env_info(env)->lti_avoid;
2461         struct dt_object **stripe = NULL;
2462         __u32 *ost_indices = NULL;
2463         ENTRY;
2464
2465         LASSERT(lo);
2466         LASSERT(lo->ldo_comp_cnt > comp_idx && lo->ldo_comp_entries != NULL);
2467         lod_comp = &lo->ldo_comp_entries[comp_idx];
2468         LASSERT(!(lod_comp->llc_flags & LCME_FL_EXTENSION));
2469
2470         /* A released component is being created */
2471         if (lod_comp->llc_pattern & LOV_PATTERN_F_RELEASED)
2472                 RETURN(0);
2473
2474         /* A Data-on-MDT component is being created */
2475         if (lov_pattern(lod_comp->llc_pattern) == LOV_PATTERN_MDT)
2476                 RETURN(0);
2477
2478         if (likely(lod_comp->llc_stripe == NULL)) {
2479                 /*
2480                  * no striping has been created so far
2481                  */
2482                 LASSERT(lod_comp->llc_stripe_count);
2483                 /*
2484                  * statfs and check OST targets now, since ld_active_tgt_count
2485                  * could be changed if some OSTs are [de]activated manually.
2486                  */
2487                 lod_qos_statfs_update(env, d, &d->lod_ost_descs);
2488                 stripe_len = lod_get_stripe_count(d, lo,
2489                                                   lod_comp->llc_stripe_count,
2490                                                   lod_comp->llc_pattern &
2491                                                   LOV_PATTERN_OVERSTRIPING);
2492
2493                 if (stripe_len == 0)
2494                         GOTO(out, rc = -ERANGE);
2495                 lod_comp->llc_stripe_count = stripe_len;
2496                 OBD_ALLOC_PTR_ARRAY(stripe, stripe_len);
2497                 if (stripe == NULL)
2498                         GOTO(out, rc = -ENOMEM);
2499                 OBD_ALLOC_PTR_ARRAY(ost_indices, stripe_len);
2500                 if (!ost_indices)
2501                         GOTO(out, rc = -ENOMEM);
2502
2503                 lod_getref(&d->lod_ost_descs);
2504                 /* XXX: support for non-0 files w/o objects */
2505                 CDEBUG(D_OTHER, "tgt_count %d stripe_count %d\n",
2506                        d->lod_ost_count, stripe_len);
2507
2508                 if (lod_comp->llc_ostlist.op_array &&
2509                     lod_comp->llc_ostlist.op_count) {
2510                         rc = lod_alloc_ost_list(env, lo, stripe, ost_indices,
2511                                                 th, comp_idx);
2512                 } else if (lod_comp->llc_stripe_offset == LOV_OFFSET_DEFAULT) {
2513                         /**
2514                          * collect OSTs and OSSs used in other mirrors whose
2515                          * components cross the ldo_comp_entries[comp_idx]
2516                          */
2517                         rc = lod_prepare_avoidance(env, lo);
2518                         if (rc)
2519                                 GOTO(put_ldts, rc);
2520
2521                         QOS_DEBUG("collecting conflict osts for comp[%d]\n",
2522                                   comp_idx);
2523                         lod_collect_avoidance(lo, lag, comp_idx);
2524
2525                         rc = lod_ost_alloc_qos(env, lo, stripe, ost_indices,
2526                                                flag, th, comp_idx);
2527                         if (rc == -EAGAIN)
2528                                 rc = lod_ost_alloc_rr(env, lo, stripe,
2529                                                       ost_indices, flag, th,
2530                                                       comp_idx);
2531                 } else {
2532                         rc = lod_ost_alloc_specific(env, lo, stripe,
2533                                                     ost_indices, flag, th,
2534                                                     comp_idx);
2535                 }
2536 put_ldts:
2537                 lod_putref(d, &d->lod_ost_descs);
2538                 if (rc < 0) {
2539                         for (i = 0; i < stripe_len; i++)
2540                                 if (stripe[i] != NULL)
2541                                         dt_object_put(env, stripe[i]);
2542                         lod_comp->llc_stripe_count = 0;
2543                 } else {
2544                         lod_comp->llc_stripe = stripe;
2545                         lod_comp->llc_ost_indices = ost_indices;
2546                         lod_comp->llc_stripes_allocated = stripe_len;
2547                 }
2548         } else {
2549                 /*
2550                  * lod_qos_parse_config() found supplied buf as a predefined
2551                  * striping (not a hint), so it allocated all the object
2552                  * now we need to create them
2553                  */
2554                 for (i = 0; i < lod_comp->llc_stripe_count; i++) {
2555                         struct dt_object  *o;
2556
2557                         o = lod_comp->llc_stripe[i];
2558                         LASSERT(o);
2559
2560                         rc = lod_sub_declare_create(env, o, attr, NULL,
2561                                                     NULL, th);
2562                         if (rc < 0) {
2563                                 CERROR("can't declare create: %d\n", rc);
2564                                 break;
2565                         }
2566                 }
2567                 /**
2568                  * Clear LCME_FL_INIT for the component so that
2569                  * lod_striping_create() can create the striping objects
2570                  * in replay.
2571                  */
2572                 lod_comp_unset_init(lod_comp);
2573         }
2574
2575 out:
2576         if (rc < 0) {
2577                 if (stripe)
2578                         OBD_FREE_PTR_ARRAY(stripe, stripe_len);
2579                 if (ost_indices)
2580                         OBD_FREE_PTR_ARRAY(ost_indices, stripe_len);
2581         }
2582         RETURN(rc);
2583 }
2584
2585 int lod_prepare_create(const struct lu_env *env, struct lod_object *lo,
2586                        struct lu_attr *attr, const struct lu_buf *buf,
2587                        struct thandle *th)
2588
2589 {
2590         struct lod_device *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
2591         uint64_t size = 0;
2592         int i;
2593         int rc;
2594         ENTRY;
2595
2596         LASSERT(lo);
2597
2598         /* no OST available */
2599         /* XXX: should we be waiting a bit to prevent failures during
2600          * cluster initialization? */
2601         if (!d->lod_ost_count)
2602                 RETURN(-EIO);
2603
2604         /*
2605          * by this time, the object's ldo_stripe_count and ldo_stripe_size
2606          * contain default value for striping: taken from the parent
2607          * or from filesystem defaults
2608          *
2609          * in case the caller is passing lovea with new striping config,
2610          * we may need to parse lovea and apply new configuration
2611          */
2612         rc = lod_qos_parse_config(env, lo, buf);
2613         if (rc)
2614                 RETURN(rc);
2615
2616         if (attr->la_valid & LA_SIZE)
2617                 size = attr->la_size;
2618
2619         /**
2620          * prepare OST object creation for the component covering file's
2621          * size, the 1st component (including plain layout file) is always
2622          * instantiated.
2623          */
2624         for (i = 0; i < lo->ldo_comp_cnt; i++) {
2625                 struct lod_layout_component *lod_comp;
2626                 struct lu_extent *extent;
2627
2628                 lod_comp = &lo->ldo_comp_entries[i];
2629                 extent = &lod_comp->llc_extent;
2630                 QOS_DEBUG("comp[%d] %lld "DEXT"\n", i, size, PEXT(extent));
2631                 if (!lo->ldo_is_composite || size >= extent->e_start) {
2632                         rc = lod_qos_prep_create(env, lo, attr, th, i);
2633                         if (rc)
2634                                 break;
2635                 }
2636         }
2637
2638         RETURN(rc);
2639 }