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