Whamcloud - gitweb
LU-7136 test: allow more time for copytools to stop
[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, 2015, 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 <libcfs/libcfs.h>
42 #include <obd_class.h>
43 #include <lustre/lustre_idl.h>
44 #include "lod_internal.h"
45
46 /*
47  * force QoS policy (not RR) to be used for testing purposes
48  */
49 #define FORCE_QOS_
50
51 #define D_QOS   D_OTHER
52
53 #define QOS_DEBUG(fmt, ...)     CDEBUG(D_QOS, fmt, ## __VA_ARGS__)
54 #define QOS_CONSOLE(fmt, ...)   LCONSOLE(D_QOS, fmt, ## __VA_ARGS__)
55
56 #define TGT_BAVAIL(i) (OST_TGT(lod,i)->ltd_statfs.os_bavail * \
57                        OST_TGT(lod,i)->ltd_statfs.os_bsize)
58
59 /**
60  * Add a new target to Quality of Service (QoS) target table.
61  *
62  * Add a new OST target to the structure representing an OSS. Resort the list
63  * of known OSSs by the number of OSTs attached to each OSS. The OSS list is
64  * protected internally and no external locking is required.
65  *
66  * \param[in] lod               LOD device
67  * \param[in] ost_desc          OST description
68  *
69  * \retval 0                    on success
70  * \retval -ENOMEM              on error
71  */
72 int qos_add_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
73 {
74         struct lod_qos_oss *oss = NULL, *temposs;
75         struct obd_export  *exp = ost_desc->ltd_exp;
76         int                 rc = 0, found = 0;
77         struct list_head   *list;
78         ENTRY;
79
80         down_write(&lod->lod_qos.lq_rw_sem);
81         /*
82          * a bit hacky approach to learn NID of corresponding connection
83          * but there is no official API to access information like this
84          * with OSD API.
85          */
86         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
87                 if (obd_uuid_equals(&oss->lqo_uuid,
88                                     &exp->exp_connection->c_remote_uuid)) {
89                         found++;
90                         break;
91                 }
92         }
93
94         if (!found) {
95                 OBD_ALLOC_PTR(oss);
96                 if (!oss)
97                         GOTO(out, rc = -ENOMEM);
98                 memcpy(&oss->lqo_uuid, &exp->exp_connection->c_remote_uuid,
99                        sizeof(oss->lqo_uuid));
100         } else {
101                 /* Assume we have to move this one */
102                 list_del(&oss->lqo_oss_list);
103         }
104
105         oss->lqo_ost_count++;
106         ost_desc->ltd_qos.ltq_oss = oss;
107
108         CDEBUG(D_QOS, "add tgt %s to OSS %s (%d OSTs)\n",
109                obd_uuid2str(&ost_desc->ltd_uuid), obd_uuid2str(&oss->lqo_uuid),
110                oss->lqo_ost_count);
111
112         /* Add sorted by # of OSTs.  Find the first entry that we're
113            bigger than... */
114         list = &lod->lod_qos.lq_oss_list;
115         list_for_each_entry(temposs, list, lqo_oss_list) {
116                 if (oss->lqo_ost_count > temposs->lqo_ost_count)
117                         break;
118         }
119         /* ...and add before it.  If we're the first or smallest, temposs
120            points to the list head, and we add to the end. */
121         list_add_tail(&oss->lqo_oss_list, &temposs->lqo_oss_list);
122
123         lod->lod_qos.lq_dirty = 1;
124         lod->lod_qos.lq_rr.lqr_dirty = 1;
125
126 out:
127         up_write(&lod->lod_qos.lq_rw_sem);
128         RETURN(rc);
129 }
130
131 /**
132  * Remove OST target from QoS table.
133  *
134  * Removes given OST target from QoS table and releases related OSS structure
135  * if no OSTs remain on the OSS.
136  *
137  * \param[in] lod               LOD device
138  * \param[in] ost_desc          OST description
139  *
140  * \retval 0                    on success
141  * \retval -ENOENT              if no OSS was found
142  */
143 int qos_del_tgt(struct lod_device *lod, struct lod_tgt_desc *ost_desc)
144 {
145         struct lod_qos_oss *oss;
146         int                 rc = 0;
147         ENTRY;
148
149         down_write(&lod->lod_qos.lq_rw_sem);
150         oss = ost_desc->ltd_qos.ltq_oss;
151         if (!oss)
152                 GOTO(out, rc = -ENOENT);
153
154         oss->lqo_ost_count--;
155         if (oss->lqo_ost_count == 0) {
156                 CDEBUG(D_QOS, "removing OSS %s\n",
157                        obd_uuid2str(&oss->lqo_uuid));
158                 list_del(&oss->lqo_oss_list);
159                 ost_desc->ltd_qos.ltq_oss = NULL;
160                 OBD_FREE_PTR(oss);
161         }
162
163         lod->lod_qos.lq_dirty = 1;
164         lod->lod_qos.lq_rr.lqr_dirty = 1;
165 out:
166         up_write(&lod->lod_qos.lq_rw_sem);
167         RETURN(rc);
168 }
169
170 /**
171  * Check whether the target is available for new OST objects.
172  *
173  * Request statfs data from the given target and verify it's active and not
174  * read-only. If so, then it can be used to place new OST objects. This
175  * function also maintains the number of active/inactive targets and sets
176  * dirty flags if those numbers change so others can run re-balance procedures.
177  * No external locking is required.
178  *
179  * \param[in] env       execution environment for this thread
180  * \param[in] d         LOD device
181  * \param[in] index     index of OST target to check
182  * \param[out] sfs      buffer for statfs data
183  *
184  * \retval 0            if the target is good
185  * \retval negative     negated errno on error
186
187  */
188 static int lod_statfs_and_check(const struct lu_env *env, struct lod_device *d,
189                                 int index, struct obd_statfs *sfs)
190 {
191         struct lod_tgt_desc *ost;
192         int                  rc;
193         ENTRY;
194
195         LASSERT(d);
196         ost = OST_TGT(d,index);
197         LASSERT(ost);
198
199         rc = dt_statfs(env, ost->ltd_ost, sfs);
200         if (rc && rc != -ENOTCONN)
201                 CERROR("%s: statfs: rc = %d\n", lod2obd(d)->obd_name, rc);
202
203         /* If the OST is readonly then we can't allocate objects there */
204         if (sfs->os_state & OS_STATE_READONLY)
205                 rc = -EROFS;
206
207         /* check whether device has changed state (active, inactive) */
208         if (rc != 0 && ost->ltd_active) {
209                 /* turned inactive? */
210                 spin_lock(&d->lod_desc_lock);
211                 if (ost->ltd_active) {
212                         ost->ltd_active = 0;
213                         LASSERT(d->lod_desc.ld_active_tgt_count > 0);
214                         d->lod_desc.ld_active_tgt_count--;
215                         d->lod_qos.lq_dirty = 1;
216                         d->lod_qos.lq_rr.lqr_dirty = 1;
217                         CDEBUG(D_CONFIG, "%s: turns inactive\n",
218                                ost->ltd_exp->exp_obd->obd_name);
219                 }
220                 spin_unlock(&d->lod_desc_lock);
221         } else if (rc == 0 && ost->ltd_active == 0) {
222                 /* turned active? */
223                 LASSERTF(d->lod_desc.ld_active_tgt_count < d->lod_ostnr,
224                          "active tgt count %d, ost nr %d\n",
225                          d->lod_desc.ld_active_tgt_count, d->lod_ostnr);
226                 spin_lock(&d->lod_desc_lock);
227                 if (ost->ltd_active == 0) {
228                         ost->ltd_active = 1;
229                         d->lod_desc.ld_active_tgt_count++;
230                         d->lod_qos.lq_dirty = 1;
231                         d->lod_qos.lq_rr.lqr_dirty = 1;
232                         CDEBUG(D_CONFIG, "%s: turns active\n",
233                                ost->ltd_exp->exp_obd->obd_name);
234                 }
235                 spin_unlock(&d->lod_desc_lock);
236         }
237
238         RETURN(rc);
239 }
240
241 /**
242  * Maintain per-target statfs data.
243  *
244  * The function refreshes statfs data for all the targets every N seconds.
245  * The actual N is controlled via procfs and set to LOV_DESC_QOS_MAXAGE_DEFAULT
246  * initially.
247  *
248  * \param[in] env       execution environment for this thread
249  * \param[in] lod       LOD device
250  */
251 static void lod_qos_statfs_update(const struct lu_env *env,
252                                   struct lod_device *lod)
253 {
254         struct obd_device *obd = lod2obd(lod);
255         struct ost_pool   *osts = &(lod->lod_pool_info);
256         unsigned int       i;
257         int                idx;
258         __u64              max_age, avail;
259         ENTRY;
260
261         max_age = cfs_time_shift_64(-2 * lod->lod_desc.ld_qos_maxage);
262
263         if (cfs_time_beforeq_64(max_age, obd->obd_osfs_age))
264                 /* statfs data are quite recent, don't need to refresh it */
265                 RETURN_EXIT;
266
267         down_write(&lod->lod_qos.lq_rw_sem);
268         if (cfs_time_beforeq_64(max_age, obd->obd_osfs_age))
269                 goto out;
270
271         for (i = 0; i < osts->op_count; i++) {
272                 idx = osts->op_array[i];
273                 avail = OST_TGT(lod,idx)->ltd_statfs.os_bavail;
274                 if (lod_statfs_and_check(env, lod, idx,
275                                          &OST_TGT(lod, idx)->ltd_statfs))
276                         continue;
277                 if (OST_TGT(lod,idx)->ltd_statfs.os_bavail != avail)
278                         /* recalculate weigths */
279                         lod->lod_qos.lq_dirty = 1;
280         }
281         obd->obd_osfs_age = cfs_time_current_64();
282
283 out:
284         up_write(&lod->lod_qos.lq_rw_sem);
285         EXIT;
286 }
287
288 /**
289  * Calculate per-OST and per-OSS penalties
290  *
291  * Re-calculate penalties when the configuration changes, active targets
292  * change and after statfs refresh (all these are reflected by lq_dirty flag).
293  * On every OST and OSS: decay the penalty by half for every 8x the update
294  * interval that the device has been idle. That gives lots of time for the
295  * statfs information to be updated (which the penalty is only a proxy for),
296  * and avoids penalizing OSS/OSTs under light load.
297  * See lod_qos_calc_weight() for how penalties are factored into the weight.
298  *
299  * \param[in] lod       LOD device
300  *
301  * \retval 0            on success
302  * \retval -EAGAIN      the number of OSTs isn't enough
303  */
304 static int lod_qos_calc_ppo(struct lod_device *lod)
305 {
306         struct lod_qos_oss *oss;
307         __u64               ba_max, ba_min, temp;
308         __u32               num_active;
309         unsigned int        i;
310         int                 rc, prio_wide;
311         time_t              now, age;
312         ENTRY;
313
314         if (!lod->lod_qos.lq_dirty)
315                 GOTO(out, rc = 0);
316
317         num_active = lod->lod_desc.ld_active_tgt_count - 1;
318         if (num_active < 1)
319                 GOTO(out, rc = -EAGAIN);
320
321         /* find bavail on each OSS */
322         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list)
323                             oss->lqo_bavail = 0;
324         lod->lod_qos.lq_active_oss_count = 0;
325
326         /*
327          * How badly user wants to select OSTs "widely" (not recently chosen
328          * and not on recent OSS's).  As opposed to "freely" (free space
329          * avail.) 0-256
330          */
331         prio_wide = 256 - lod->lod_qos.lq_prio_free;
332
333         ba_min = (__u64)(-1);
334         ba_max = 0;
335         now = cfs_time_current_sec();
336         /* Calculate OST penalty per object
337          * (lod ref taken in lod_qos_prep_create()) */
338         cfs_foreach_bit(lod->lod_ost_bitmap, i) {
339                 LASSERT(OST_TGT(lod,i));
340                 temp = TGT_BAVAIL(i);
341                 if (!temp)
342                         continue;
343                 ba_min = min(temp, ba_min);
344                 ba_max = max(temp, ba_max);
345
346                 /* Count the number of usable OSS's */
347                 if (OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail == 0)
348                         lod->lod_qos.lq_active_oss_count++;
349                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_bavail += temp;
350
351                 /* per-OST penalty is prio * TGT_bavail / (num_ost - 1) / 2 */
352                 temp >>= 1;
353                 do_div(temp, num_active);
354                 OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj =
355                         (temp * prio_wide) >> 8;
356
357                 age = (now - OST_TGT(lod,i)->ltd_qos.ltq_used) >> 3;
358                 if (lod->lod_qos.lq_reset ||
359                     age > 32 * lod->lod_desc.ld_qos_maxage)
360                         OST_TGT(lod,i)->ltd_qos.ltq_penalty = 0;
361                 else if (age > lod->lod_desc.ld_qos_maxage)
362                         /* Decay OST penalty. */
363                         OST_TGT(lod,i)->ltd_qos.ltq_penalty >>=
364                                 (age / lod->lod_desc.ld_qos_maxage);
365         }
366
367         num_active = lod->lod_qos.lq_active_oss_count - 1;
368         if (num_active < 1) {
369                 /* If there's only 1 OSS, we can't penalize it, so instead
370                    we have to double the OST penalty */
371                 num_active = 1;
372                 cfs_foreach_bit(lod->lod_ost_bitmap, i)
373                         OST_TGT(lod,i)->ltd_qos.ltq_penalty_per_obj <<= 1;
374         }
375
376         /* Per-OSS penalty is prio * oss_avail / oss_osts / (num_oss - 1) / 2 */
377         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
378                 temp = oss->lqo_bavail >> 1;
379                 do_div(temp, oss->lqo_ost_count * num_active);
380                 oss->lqo_penalty_per_obj = (temp * prio_wide) >> 8;
381
382                 age = (now - oss->lqo_used) >> 3;
383                 if (lod->lod_qos.lq_reset ||
384                     age > 32 * lod->lod_desc.ld_qos_maxage)
385                         oss->lqo_penalty = 0;
386                 else if (age > lod->lod_desc.ld_qos_maxage)
387                         /* Decay OSS penalty. */
388                         oss->lqo_penalty >>= age / lod->lod_desc.ld_qos_maxage;
389         }
390
391         lod->lod_qos.lq_dirty = 0;
392         lod->lod_qos.lq_reset = 0;
393
394         /* If each ost has almost same free space,
395          * do rr allocation for better creation performance */
396         lod->lod_qos.lq_same_space = 0;
397         if ((ba_max * (256 - lod->lod_qos.lq_threshold_rr)) >> 8 < ba_min) {
398                 lod->lod_qos.lq_same_space = 1;
399                 /* Reset weights for the next time we enter qos mode */
400                 lod->lod_qos.lq_reset = 1;
401         }
402         rc = 0;
403
404 out:
405 #ifndef FORCE_QOS
406         if (!rc && lod->lod_qos.lq_same_space)
407                 RETURN(-EAGAIN);
408 #endif
409         RETURN(rc);
410 }
411
412 /**
413  * Calculate weight for a given OST target.
414  *
415  * The final OST weight is the number of bytes available minus the OST and
416  * OSS penalties.  See lod_qos_calc_ppo() for how penalties are calculated.
417  *
418  * \param[in] lod       LOD device, where OST targets are listed
419  * \param[in] i         OST target index
420  *
421  * \retval              0
422  */
423 static int lod_qos_calc_weight(struct lod_device *lod, int i)
424 {
425         __u64 temp, temp2;
426
427         temp = TGT_BAVAIL(i);
428         temp2 = OST_TGT(lod,i)->ltd_qos.ltq_penalty +
429                 OST_TGT(lod,i)->ltd_qos.ltq_oss->lqo_penalty;
430         if (temp < temp2)
431                 OST_TGT(lod,i)->ltd_qos.ltq_weight = 0;
432         else
433                 OST_TGT(lod,i)->ltd_qos.ltq_weight = temp - temp2;
434         return 0;
435 }
436
437 /**
438  * Re-calculate weights.
439  *
440  * The function is called when some OST target was used for a new object. In
441  * this case we should re-calculate all the weights to keep new allocations
442  * balanced well.
443  *
444  * \param[in] lod       LOD device
445  * \param[in] osts      OST pool where a new object was placed
446  * \param[in] index     OST target where a new object was placed
447  * \param[out] total_wt new total weight for the pool
448  *
449  * \retval              0
450  */
451 static int lod_qos_used(struct lod_device *lod, struct ost_pool *osts,
452                         __u32 index, __u64 *total_wt)
453 {
454         struct lod_tgt_desc *ost;
455         struct lod_qos_oss  *oss;
456         unsigned int j;
457         ENTRY;
458
459         ost = OST_TGT(lod,index);
460         LASSERT(ost);
461
462         /* Don't allocate on this devuce anymore, until the next alloc_qos */
463         ost->ltd_qos.ltq_usable = 0;
464
465         oss = ost->ltd_qos.ltq_oss;
466
467         /* Decay old penalty by half (we're adding max penalty, and don't
468            want it to run away.) */
469         ost->ltd_qos.ltq_penalty >>= 1;
470         oss->lqo_penalty >>= 1;
471
472         /* mark the OSS and OST as recently used */
473         ost->ltd_qos.ltq_used = oss->lqo_used = cfs_time_current_sec();
474
475         /* Set max penalties for this OST and OSS */
476         ost->ltd_qos.ltq_penalty +=
477                 ost->ltd_qos.ltq_penalty_per_obj * lod->lod_ostnr;
478         oss->lqo_penalty += oss->lqo_penalty_per_obj *
479                 lod->lod_qos.lq_active_oss_count;
480
481         /* Decrease all OSS penalties */
482         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
483                 if (oss->lqo_penalty < oss->lqo_penalty_per_obj)
484                         oss->lqo_penalty = 0;
485                 else
486                         oss->lqo_penalty -= oss->lqo_penalty_per_obj;
487         }
488
489         *total_wt = 0;
490         /* Decrease all OST penalties */
491         for (j = 0; j < osts->op_count; j++) {
492                 int i;
493
494                 i = osts->op_array[j];
495                 if (!cfs_bitmap_check(lod->lod_ost_bitmap, i))
496                         continue;
497
498                 ost = OST_TGT(lod,i);
499                 LASSERT(ost);
500
501                 if (ost->ltd_qos.ltq_penalty <
502                                 ost->ltd_qos.ltq_penalty_per_obj)
503                         ost->ltd_qos.ltq_penalty = 0;
504                 else
505                         ost->ltd_qos.ltq_penalty -=
506                                 ost->ltd_qos.ltq_penalty_per_obj;
507
508                 lod_qos_calc_weight(lod, i);
509
510                 /* Recalc the total weight of usable osts */
511                 if (ost->ltd_qos.ltq_usable)
512                         *total_wt += ost->ltd_qos.ltq_weight;
513
514                 QOS_DEBUG("recalc tgt %d usable=%d avail="LPU64
515                           " ostppo="LPU64" ostp="LPU64" ossppo="LPU64
516                           " ossp="LPU64" wt="LPU64"\n",
517                           i, ost->ltd_qos.ltq_usable, TGT_BAVAIL(i) >> 10,
518                           ost->ltd_qos.ltq_penalty_per_obj >> 10,
519                           ost->ltd_qos.ltq_penalty >> 10,
520                           ost->ltd_qos.ltq_oss->lqo_penalty_per_obj >> 10,
521                           ost->ltd_qos.ltq_oss->lqo_penalty >> 10,
522                           ost->ltd_qos.ltq_weight >> 10);
523         }
524
525         RETURN(0);
526 }
527
528 void lod_qos_rr_init(struct lod_qos_rr *lqr)
529 {
530         spin_lock_init(&lqr->lqr_alloc);
531         lqr->lqr_dirty = 1;
532 }
533
534
535 #define LOV_QOS_EMPTY ((__u32)-1)
536
537 /**
538  * Calculate optimal round-robin order with regard to OSSes.
539  *
540  * Place all the OSTs from pool \a src_pool in a special array to be used for
541  * round-robin (RR) stripe allocation.  The placement algorithm interleaves
542  * OSTs from the different OSSs so that RR allocation can balance OSSs evenly.
543  * Resorts the targets when the number of active targets changes (because of
544  * a new target or activation/deactivation).
545  *
546  * \param[in] lod       LOD device
547  * \param[in] src_pool  OST pool
548  * \param[in] lqr       round-robin list
549  *
550  * \retval 0            on success
551  * \retval -ENOMEM      fails to allocate the array
552  */
553 static int lod_qos_calc_rr(struct lod_device *lod, struct ost_pool *src_pool,
554                            struct lod_qos_rr *lqr)
555 {
556         struct lod_qos_oss  *oss;
557         struct lod_tgt_desc *ost;
558         unsigned placed, real_count;
559         unsigned int i;
560         int rc;
561         ENTRY;
562
563         if (!lqr->lqr_dirty) {
564                 LASSERT(lqr->lqr_pool.op_size);
565                 RETURN(0);
566         }
567
568         /* Do actual allocation. */
569         down_write(&lod->lod_qos.lq_rw_sem);
570
571         /*
572          * Check again. While we were sleeping on @lq_rw_sem something could
573          * change.
574          */
575         if (!lqr->lqr_dirty) {
576                 LASSERT(lqr->lqr_pool.op_size);
577                 up_write(&lod->lod_qos.lq_rw_sem);
578                 RETURN(0);
579         }
580
581         real_count = src_pool->op_count;
582
583         /* Zero the pool array */
584         /* alloc_rr is holding a read lock on the pool, so nobody is adding/
585            deleting from the pool. The lq_rw_sem insures that nobody else
586            is reading. */
587         lqr->lqr_pool.op_count = real_count;
588         rc = lod_ost_pool_extend(&lqr->lqr_pool, real_count);
589         if (rc) {
590                 up_write(&lod->lod_qos.lq_rw_sem);
591                 RETURN(rc);
592         }
593         for (i = 0; i < lqr->lqr_pool.op_count; i++)
594                 lqr->lqr_pool.op_array[i] = LOV_QOS_EMPTY;
595
596         /* Place all the OSTs from 1 OSS at the same time. */
597         placed = 0;
598         list_for_each_entry(oss, &lod->lod_qos.lq_oss_list, lqo_oss_list) {
599                 int j = 0;
600
601                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
602                         int next;
603
604                         if (!cfs_bitmap_check(lod->lod_ost_bitmap,
605                                                 src_pool->op_array[i]))
606                                 continue;
607
608                         ost = OST_TGT(lod,src_pool->op_array[i]);
609                         LASSERT(ost && ost->ltd_ost);
610                         if (ost->ltd_qos.ltq_oss != oss)
611                                 continue;
612
613                         /* Evenly space these OSTs across arrayspace */
614                         next = j * lqr->lqr_pool.op_count / oss->lqo_ost_count;
615                         while (lqr->lqr_pool.op_array[next] != LOV_QOS_EMPTY)
616                                 next = (next + 1) % lqr->lqr_pool.op_count;
617
618                         lqr->lqr_pool.op_array[next] = src_pool->op_array[i];
619                         j++;
620                         placed++;
621                 }
622         }
623
624         lqr->lqr_dirty = 0;
625         up_write(&lod->lod_qos.lq_rw_sem);
626
627         if (placed != real_count) {
628                 /* This should never happen */
629                 LCONSOLE_ERROR_MSG(0x14e, "Failed to place all OSTs in the "
630                                    "round-robin list (%d of %d).\n",
631                                    placed, real_count);
632                 for (i = 0; i < lqr->lqr_pool.op_count; i++) {
633                         LCONSOLE(D_WARNING, "rr #%d ost idx=%d\n", i,
634                                  lqr->lqr_pool.op_array[i]);
635                 }
636                 lqr->lqr_dirty = 1;
637                 RETURN(-EAGAIN);
638         }
639
640 #if 0
641         for (i = 0; i < lqr->lqr_pool.op_count; i++)
642                 QOS_CONSOLE("rr #%d ost idx=%d\n", i, lqr->lqr_pool.op_array[i]);
643 #endif
644
645         RETURN(0);
646 }
647
648 /**
649  * Instantiate and declare creation of a new object.
650  *
651  * The function instantiates LU representation for a new object on the
652  * specified device. Also it declares an intention to create that
653  * object on the storage target.
654  *
655  * Note lu_object_anon() is used which is a trick with regard to LU/OSD
656  * infrastructure - in the existing precreation framework we can't assign FID
657  * at this moment, we do this later once a transaction is started. So the
658  * special method instantiates FID-less object in the cache and later it
659  * will get a FID and proper placement in LU cache.
660  *
661  * \param[in] env       execution environment for this thread
662  * \param[in] d         LOD device
663  * \param[in] ost_idx   OST target index where the object is being created
664  * \param[in] th        transaction handle
665  *
666  * \retval              object ptr on success, ERR_PTR() otherwise
667  */
668 static struct dt_object *lod_qos_declare_object_on(const struct lu_env *env,
669                                                    struct lod_device *d,
670                                                    __u32 ost_idx,
671                                                    struct thandle *th)
672 {
673         struct lod_tgt_desc *ost;
674         struct lu_object *o, *n;
675         struct lu_device *nd;
676         struct dt_object *dt;
677         int               rc;
678         ENTRY;
679
680         LASSERT(d);
681         LASSERT(ost_idx < d->lod_osts_size);
682         ost = OST_TGT(d,ost_idx);
683         LASSERT(ost);
684         LASSERT(ost->ltd_ost);
685
686         nd = &ost->ltd_ost->dd_lu_dev;
687
688         /*
689          * allocate anonymous object with zero fid, real fid
690          * will be assigned by OSP within transaction
691          * XXX: to be fixed with fully-functional OST fids
692          */
693         o = lu_object_anon(env, nd, NULL);
694         if (IS_ERR(o))
695                 GOTO(out, dt = ERR_PTR(PTR_ERR(o)));
696
697         n = lu_object_locate(o->lo_header, nd->ld_type);
698         if (unlikely(n == NULL)) {
699                 CERROR("can't find slice\n");
700                 lu_object_put(env, o);
701                 GOTO(out, dt = ERR_PTR(-EINVAL));
702         }
703
704         dt = container_of(n, struct dt_object, do_lu);
705
706         rc = lod_sub_object_declare_create(env, dt, NULL, NULL, NULL, th);
707         if (rc < 0) {
708                 CDEBUG(D_OTHER, "can't declare creation on #%u: %d\n",
709                        ost_idx, rc);
710                 lu_object_put(env, o);
711                 dt = ERR_PTR(rc);
712         }
713
714 out:
715         RETURN(dt);
716 }
717
718 /**
719  * Calculate a minimum acceptable stripe count.
720  *
721  * Return an acceptable stripe count depending on flag LOV_USES_DEFAULT_STRIPE:
722  * all stripes or 3/4 of stripes.
723  *
724  * \param[in] stripe_cnt        number of stripes requested
725  * \param[in] flags             0 or LOV_USES_DEFAULT_STRIPE
726  *
727  * \retval                      acceptable stripecount
728  */
729 static int min_stripe_count(__u32 stripe_cnt, int flags)
730 {
731         return (flags & LOV_USES_DEFAULT_STRIPE ?
732                         stripe_cnt - (stripe_cnt / 4) : stripe_cnt);
733 }
734
735 #define LOV_CREATE_RESEED_MULT 30
736 #define LOV_CREATE_RESEED_MIN  2000
737
738 /**
739  * Check if an OST is full.
740  *
741  * Check whether an OST should be considered full based
742  * on the given statfs data.
743  *
744  * \param[in] msfs      statfs data
745  *
746  * \retval false        not full
747  * \retval true         full
748  */
749 static int inline lod_qos_dev_is_full(struct obd_statfs *msfs)
750 {
751         __u64 used;
752         int   bs = msfs->os_bsize;
753
754         LASSERT(((bs - 1) & bs) == 0);
755
756         /* the minimum of 0.1% used blocks and 1GB bytes. */
757         used = min_t(__u64, (msfs->os_blocks - msfs->os_bfree) >> 10,
758                         1 << (31 - ffs(bs)));
759         return (msfs->os_bavail < used);
760 }
761
762 /**
763  * Initialize temporary OST-in-use array.
764  *
765  * Allocate or extend the array used to mark targets already assigned to a new
766  * striping so they are not used more than once.
767  *
768  * \param[in] env       execution environment for this thread
769  * \param[in] stripes   number of items needed in the array
770  *
771  * \retval 0            on success
772  * \retval -ENOMEM      on error
773  */
774 static inline int lod_qos_ost_in_use_clear(const struct lu_env *env,
775                                            __u32 stripes)
776 {
777         struct lod_thread_info *info = lod_env_info(env);
778
779         if (info->lti_ea_store_size < sizeof(int) * stripes)
780                 lod_ea_store_resize(info, stripes * sizeof(int));
781         if (info->lti_ea_store_size < sizeof(int) * stripes) {
782                 CERROR("can't allocate memory for ost-in-use array\n");
783                 return -ENOMEM;
784         }
785         memset(info->lti_ea_store, -1, sizeof(int) * stripes);
786         return 0;
787 }
788
789 /**
790  * Remember a target in the array of used targets.
791  *
792  * Mark the given target as used for a new striping being created. The status
793  * of an OST in a striping can be checked with lod_qos_is_ost_used().
794  *
795  * \param[in] env       execution environment for this thread
796  * \param[in] idx       index in the array
797  * \param[in] ost       OST target index to mark as used
798  */
799 static inline void lod_qos_ost_in_use(const struct lu_env *env,
800                                       int idx, int ost)
801 {
802         struct lod_thread_info *info = lod_env_info(env);
803         int *osts = info->lti_ea_store;
804
805         LASSERT(info->lti_ea_store_size >= idx * sizeof(int));
806         osts[idx] = ost;
807 }
808
809 /**
810  * Check is OST used in a striping.
811  *
812  * Checks whether OST with the given index is marked as used in the temporary
813  * array (see lod_qos_ost_in_use()).
814  *
815  * \param[in] env       execution environment for this thread
816  * \param[in] ost       OST target index to check
817  * \param[in] stripes   the number of items used in the array already
818  *
819  * \retval 0            not used
820  * \retval 1            used
821  */
822 static int lod_qos_is_ost_used(const struct lu_env *env, int ost, __u32 stripes)
823 {
824         struct lod_thread_info *info = lod_env_info(env);
825         int *osts = info->lti_ea_store;
826         __u32 j;
827
828         for (j = 0; j < stripes; j++) {
829                 if (osts[j] == ost)
830                         return 1;
831         }
832         return 0;
833 }
834
835 static int lod_check_and_reserve_ost(const struct lu_env *env,
836                                      struct lod_device *m,
837                                      struct obd_statfs *sfs, __u32 ost_idx,
838                                      __u32 speed, __u32 *s_idx,
839                                      struct dt_object **stripe,
840                                      struct thandle *th)
841 {
842         struct dt_object   *o;
843         __u32 stripe_idx = *s_idx;
844         int rc;
845
846         rc = lod_statfs_and_check(env, m, ost_idx, sfs);
847         if (rc) {
848                 /* this OSP doesn't feel well */
849                 goto out_return;
850         }
851
852         /*
853          * skip full devices
854          */
855         if (lod_qos_dev_is_full(sfs)) {
856                 QOS_DEBUG("#%d is full\n", ost_idx);
857                 goto out_return;
858         }
859
860         /*
861          * We expect number of precreated objects in f_ffree at
862          * the first iteration, skip OSPs with no objects ready
863          */
864         if (sfs->os_fprecreated == 0 && speed == 0) {
865                 QOS_DEBUG("#%d: precreation is empty\n", ost_idx);
866                 goto out_return;
867         }
868
869         /*
870          * try to use another OSP if this one is degraded
871          */
872         if (sfs->os_state & OS_STATE_DEGRADED && speed < 2) {
873                 QOS_DEBUG("#%d: degraded\n", ost_idx);
874                 goto out_return;
875         }
876
877         /*
878          * do not put >1 objects on a single OST
879          */
880         if (speed && lod_qos_is_ost_used(env, ost_idx, stripe_idx))
881                 goto out_return;
882
883         o = lod_qos_declare_object_on(env, m, ost_idx, th);
884         if (IS_ERR(o)) {
885                 CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
886                        ost_idx, (int) PTR_ERR(o));
887                 rc = PTR_ERR(o);
888                 goto out_return;
889         }
890
891         /*
892          * We've successfully declared (reserved) an object
893          */
894         lod_qos_ost_in_use(env, stripe_idx, ost_idx);
895         stripe[stripe_idx] = o;
896         stripe_idx++;
897         *s_idx = stripe_idx;
898
899 out_return:
900         return rc;
901 }
902
903 /**
904  * Allocate a striping using round-robin algorithm.
905  *
906  * Allocates a new striping using round-robin algorithm. The function refreshes
907  * all the internal structures (statfs cache, array of available OSTs sorted
908  * with regard to OSS, etc). The number of stripes required is taken from the
909  * object (must be prepared by the caller), but can change if the flag
910  * LOV_USES_DEFAULT_STRIPE is supplied. The caller should ensure nobody else
911  * is trying to create a striping on the object in parallel. All the internal
912  * structures (like pools, etc) are protected and no additional locking is
913  * required. The function succeeds even if a single stripe is allocated. To save
914  * time we give priority to targets which already have objects precreated.
915  * Full OSTs are skipped (see lod_qos_dev_is_full() for the details).
916  *
917  * \param[in] env       execution environment for this thread
918  * \param[in] lo        LOD object
919  * \param[out] stripe   striping created
920  * \param[in] flags     allocation flags (0 or LOV_USES_DEFAULT_STRIPE)
921  * \param[in] th        transaction handle
922  *
923  * \retval 0            on success
924  * \retval -ENOSPC      if not enough OSTs are found
925  * \retval negative     negated errno for other failures
926  */
927 static int lod_alloc_rr(const struct lu_env *env, struct lod_object *lo,
928                         struct dt_object **stripe, int flags,
929                         struct thandle *th)
930 {
931         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
932         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
933         struct pool_desc  *pool = NULL;
934         struct ost_pool   *osts;
935         struct lod_qos_rr *lqr;
936         unsigned int       i, array_idx;
937         int                rc;
938         __u32              ost_start_idx_temp;
939         int                speed = 0;
940         __u32              stripe_idx = 0;
941         __u32              stripe_cnt = lo->ldo_stripenr;
942         __u32              stripe_cnt_min = min_stripe_count(stripe_cnt, flags);
943         __u32              ost_idx;
944         ENTRY;
945
946         if (lo->ldo_pool)
947                 pool = lod_find_pool(m, lo->ldo_pool);
948
949         if (pool != NULL) {
950                 down_read(&pool_tgt_rw_sem(pool));
951                 osts = &(pool->pool_obds);
952                 lqr = &(pool->pool_rr);
953         } else {
954                 osts = &(m->lod_pool_info);
955                 lqr = &(m->lod_qos.lq_rr);
956         }
957
958         rc = lod_qos_calc_rr(m, osts, lqr);
959         if (rc)
960                 GOTO(out, rc);
961
962         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
963         if (rc)
964                 GOTO(out, rc);
965
966         down_read(&m->lod_qos.lq_rw_sem);
967         spin_lock(&lqr->lqr_alloc);
968         if (--lqr->lqr_start_count <= 0) {
969                 lqr->lqr_start_idx = cfs_rand() % osts->op_count;
970                 lqr->lqr_start_count =
971                         (LOV_CREATE_RESEED_MIN / max(osts->op_count, 1U) +
972                          LOV_CREATE_RESEED_MULT) * max(osts->op_count, 1U);
973         } else if (stripe_cnt_min >= osts->op_count ||
974                         lqr->lqr_start_idx > osts->op_count) {
975                 /* If we have allocated from all of the OSTs, slowly
976                  * precess the next start if the OST/stripe count isn't
977                  * already doing this for us. */
978                 lqr->lqr_start_idx %= osts->op_count;
979                 if (stripe_cnt > 1 && (osts->op_count % stripe_cnt) != 1)
980                         ++lqr->lqr_offset_idx;
981         }
982         ost_start_idx_temp = lqr->lqr_start_idx;
983
984 repeat_find:
985
986         QOS_DEBUG("pool '%s' want %d startidx %d startcnt %d offset %d "
987                   "active %d count %d\n",
988                   lo->ldo_pool ? lo->ldo_pool : "",
989                   stripe_cnt, lqr->lqr_start_idx, lqr->lqr_start_count,
990                   lqr->lqr_offset_idx, osts->op_count, osts->op_count);
991
992         for (i = 0; i < osts->op_count && stripe_idx < lo->ldo_stripenr; i++) {
993                 array_idx = (lqr->lqr_start_idx + lqr->lqr_offset_idx) %
994                                 osts->op_count;
995                 ++lqr->lqr_start_idx;
996                 ost_idx = lqr->lqr_pool.op_array[array_idx];
997
998                 QOS_DEBUG("#%d strt %d act %d strp %d ary %d idx %d\n",
999                           i, lqr->lqr_start_idx, /* XXX: active*/ 0,
1000                           stripe_idx, array_idx, ost_idx);
1001
1002                 if ((ost_idx == LOV_QOS_EMPTY) ||
1003                     !cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1004                         continue;
1005
1006                 /* Fail Check before osc_precreate() is called
1007                    so we can only 'fail' single OSC. */
1008                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1009                         continue;
1010
1011                 spin_unlock(&lqr->lqr_alloc);
1012                 rc = lod_check_and_reserve_ost(env, m, sfs, ost_idx, speed,
1013                                                &stripe_idx, stripe, th);
1014                 spin_lock(&lqr->lqr_alloc);
1015         }
1016         if ((speed < 2) && (stripe_idx < stripe_cnt_min)) {
1017                 /* Try again, allowing slower OSCs */
1018                 speed++;
1019                 lqr->lqr_start_idx = ost_start_idx_temp;
1020                 goto repeat_find;
1021         }
1022
1023         spin_unlock(&lqr->lqr_alloc);
1024         up_read(&m->lod_qos.lq_rw_sem);
1025
1026         if (stripe_idx) {
1027                 lo->ldo_stripenr = stripe_idx;
1028                 /* at least one stripe is allocated */
1029                 rc = 0;
1030         } else {
1031                 /* nobody provided us with a single object */
1032                 rc = -ENOSPC;
1033         }
1034
1035 out:
1036         if (pool != NULL) {
1037                 up_read(&pool_tgt_rw_sem(pool));
1038                 /* put back ref got by lod_find_pool() */
1039                 lod_pool_putref(pool);
1040         }
1041
1042         RETURN(rc);
1043 }
1044
1045 /**
1046  * Allocate a specific striping layout on a user defined set of OSTs.
1047  *
1048  * Allocates new striping using the OST index range provided by the data from
1049  * the lmm_obejcts contained in the lov_user_md passed to this method. Full
1050  * OSTs are not considered. The exact order of OSTs requested by the user
1051  * is respected as much as possible depending on OST status. The number of
1052  * stripes needed and stripe offset are taken from the object. If that number
1053  * can not be met, then the function returns a failure and then it's the
1054  * caller's responsibility to release the stripes allocated. All the internal
1055  * structures are protected, but no concurrent allocation is allowed on the
1056  * same objects.
1057  *
1058  * \param[in] env       execution environment for this thread
1059  * \param[in] lo        LOD object
1060  * \param[out] stripe   striping created
1061  * \param[in] lum       stripe md to specify list of OSTs
1062  * \param[in] th        transaction handle
1063  *
1064  * \retval 0            on success
1065  * \retval -ENODEV      OST index does not exist on file system
1066  * \retval -EINVAL      requested OST index is invalid
1067  * \retval negative     negated errno on error
1068  */
1069 static int lod_alloc_ost_list(const struct lu_env *env,
1070                               struct lod_object *lo, struct dt_object **stripe,
1071                               struct lov_user_md *lum, struct thandle *th)
1072 {
1073         struct lod_device       *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1074         struct obd_statfs       *sfs = &lod_env_info(env)->lti_osfs;
1075         struct dt_object        *o;
1076         struct lov_user_md_v3   *v3;
1077         unsigned int            array_idx = 0;
1078         int                     stripe_count = 0;
1079         int                     i;
1080         int                     rc;
1081         ENTRY;
1082
1083         /* for specific OSTs layout */
1084         LASSERT(lum != NULL && lum->lmm_magic == LOV_USER_MAGIC_SPECIFIC);
1085         lustre_print_user_md(D_OTHER, lum, __func__);
1086
1087         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1088         if (rc < 0)
1089                 RETURN(rc);
1090
1091         v3 = (struct lov_user_md_v3 *)lum;
1092         for (i = 0; i < lo->ldo_stripenr; i++) {
1093                 if (v3->lmm_objects[i].l_ost_idx == lo->ldo_def_stripe_offset) {
1094                         array_idx = i;
1095                         break;
1096                 }
1097         }
1098         if (i == lo->ldo_stripenr) {
1099                 CDEBUG(D_OTHER,
1100                        "%s: start index %d not in the specified list of OSTs\n",
1101                        lod2obd(m)->obd_name, lo->ldo_def_stripe_offset);
1102                 RETURN(-EINVAL);
1103         }
1104
1105         for (i = 0; i < lo->ldo_stripenr;
1106              i++, array_idx = (array_idx + 1) % lo->ldo_stripenr) {
1107                 __u32 ost_idx = v3->lmm_objects[array_idx].l_ost_idx;
1108
1109                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx)) {
1110                         rc = -ENODEV;
1111                         break;
1112                 }
1113
1114                 /*
1115                  * do not put >1 objects on a single OST
1116                  */
1117                 if (lod_qos_is_ost_used(env, ost_idx, stripe_count)) {
1118                         rc = -EINVAL;
1119                         break;
1120                 }
1121
1122                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1123                 if (rc < 0) /* this OSP doesn't feel well */
1124                         break;
1125
1126                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1127                 if (IS_ERR(o)) {
1128                         rc = PTR_ERR(o);
1129                         CDEBUG(D_OTHER,
1130                                "%s: can't declare new object on #%u: %d\n",
1131                                lod2obd(m)->obd_name, ost_idx, rc);
1132                         break;
1133                 }
1134
1135                 /*
1136                  * We've successfully declared (reserved) an object
1137                  */
1138                 lod_qos_ost_in_use(env, stripe_count, ost_idx);
1139                 stripe[stripe_count] = o;
1140                 stripe_count++;
1141         }
1142
1143         RETURN(rc);
1144 }
1145
1146 /**
1147  * Allocate a striping on a predefined set of OSTs.
1148  *
1149  * Allocates new layout starting from OST index in lo->ldo_def_stripe_offset.
1150  * Full OSTs are not considered. The exact order of OSTs is not important and
1151  * varies depending on OST status. The allocation procedure prefers the targets
1152  * with precreated objects ready. The number of stripes needed and stripe
1153  * offset are taken from the object. If that number cannot be met, then the
1154  * function returns an error and then it's the caller's responsibility to
1155  * release the stripes allocated. All the internal structures are protected,
1156  * but no concurrent allocation is allowed on the same objects.
1157  *
1158  * \param[in] env       execution environment for this thread
1159  * \param[in] lo        LOD object
1160  * \param[out] stripe   striping created
1161  * \param[in] flags     not used
1162  * \param[in] th        transaction handle
1163  *
1164  * \retval 0            on success
1165  * \retval -ENOSPC      if no OST objects are available at all
1166  * \retval -EFBIG       if not enough OST objects are found
1167  * \retval -EINVAL      requested offset is invalid
1168  * \retval negative     errno on failure
1169  */
1170 static int lod_alloc_specific(const struct lu_env *env, struct lod_object *lo,
1171                               struct dt_object **stripe, int flags,
1172                               struct thandle *th)
1173 {
1174         struct lod_device *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1175         struct obd_statfs *sfs = &lod_env_info(env)->lti_osfs;
1176         struct dt_object  *o;
1177         __u32              ost_idx;
1178         unsigned int       i, array_idx, ost_count;
1179         int                rc, stripe_num = 0;
1180         int                speed = 0;
1181         struct pool_desc  *pool = NULL;
1182         struct ost_pool   *osts;
1183         ENTRY;
1184
1185         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1186         if (rc)
1187                 GOTO(out, rc);
1188
1189         if (lo->ldo_pool)
1190                 pool = lod_find_pool(m, lo->ldo_pool);
1191
1192         if (pool != NULL) {
1193                 down_read(&pool_tgt_rw_sem(pool));
1194                 osts = &(pool->pool_obds);
1195         } else {
1196                 osts = &(m->lod_pool_info);
1197         }
1198
1199         ost_count = osts->op_count;
1200
1201 repeat_find:
1202         /* search loi_ost_idx in ost array */
1203         array_idx = 0;
1204         for (i = 0; i < ost_count; i++) {
1205                 if (osts->op_array[i] == lo->ldo_def_stripe_offset) {
1206                         array_idx = i;
1207                         break;
1208                 }
1209         }
1210         if (i == ost_count) {
1211                 CERROR("Start index %d not found in pool '%s'\n",
1212                        lo->ldo_def_stripe_offset,
1213                        lo->ldo_pool ? lo->ldo_pool : "");
1214                 GOTO(out, rc = -EINVAL);
1215         }
1216
1217         for (i = 0; i < ost_count;
1218                         i++, array_idx = (array_idx + 1) % ost_count) {
1219                 ost_idx = osts->op_array[array_idx];
1220
1221                 if (!cfs_bitmap_check(m->lod_ost_bitmap, ost_idx))
1222                         continue;
1223
1224                 /* Fail Check before osc_precreate() is called
1225                    so we can only 'fail' single OSC. */
1226                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) && ost_idx == 0)
1227                         continue;
1228
1229                 /*
1230                  * do not put >1 objects on a single OST
1231                  */
1232                 if (lod_qos_is_ost_used(env, ost_idx, stripe_num))
1233                         continue;
1234
1235                 /* Drop slow OSCs if we can, but not for requested start idx.
1236                  *
1237                  * This means "if OSC is slow and it is not the requested
1238                  * start OST, then it can be skipped, otherwise skip it only
1239                  * if it is inactive/recovering/out-of-space." */
1240
1241                 rc = lod_statfs_and_check(env, m, ost_idx, sfs);
1242                 if (rc) {
1243                         /* this OSP doesn't feel well */
1244                         continue;
1245                 }
1246
1247                 /*
1248                  * We expect number of precreated objects in f_ffree at
1249                  * the first iteration, skip OSPs with no objects ready
1250                  * don't apply this logic to OST specified with stripe_offset
1251                  */
1252                 if (i != 0 && sfs->os_fprecreated == 0 && speed == 0)
1253                         continue;
1254
1255                 o = lod_qos_declare_object_on(env, m, ost_idx, th);
1256                 if (IS_ERR(o)) {
1257                         CDEBUG(D_OTHER, "can't declare new object on #%u: %d\n",
1258                                ost_idx, (int) PTR_ERR(o));
1259                         continue;
1260                 }
1261
1262                 /*
1263                  * We've successfully declared (reserved) an object
1264                  */
1265                 lod_qos_ost_in_use(env, stripe_num, ost_idx);
1266                 stripe[stripe_num] = o;
1267                 stripe_num++;
1268
1269                 /* We have enough stripes */
1270                 if (stripe_num == lo->ldo_stripenr)
1271                         GOTO(out, rc = 0);
1272         }
1273         if (speed < 2) {
1274                 /* Try again, allowing slower OSCs */
1275                 speed++;
1276                 goto repeat_find;
1277         }
1278
1279         /* If we were passed specific striping params, then a failure to
1280          * meet those requirements is an error, since we can't reallocate
1281          * that memory (it might be part of a larger array or something).
1282          */
1283         CERROR("can't lstripe objid "DFID": have %d want %u\n",
1284                PFID(lu_object_fid(lod2lu_obj(lo))), stripe_num,
1285                lo->ldo_stripenr);
1286         rc = stripe_num == 0 ? -ENOSPC : -EFBIG;
1287 out:
1288         if (pool != NULL) {
1289                 up_read(&pool_tgt_rw_sem(pool));
1290                 /* put back ref got by lod_find_pool() */
1291                 lod_pool_putref(pool);
1292         }
1293
1294         RETURN(rc);
1295 }
1296
1297 /**
1298  * Check whether QoS allocation should be used.
1299  *
1300  * A simple helper to decide when QoS allocation should be used:
1301  * if it's just a single available target or the used space is
1302  * evenly distributed among the targets at the moment, then QoS
1303  * allocation algorithm should not be used.
1304  *
1305  * \param[in] lod       LOD device
1306  *
1307  * \retval 0            should not be used
1308  * \retval 1            should be used
1309  */
1310 static inline int lod_qos_is_usable(struct lod_device *lod)
1311 {
1312 #ifdef FORCE_QOS
1313         /* to be able to debug QoS code */
1314         return 1;
1315 #endif
1316
1317         /* Detect -EAGAIN early, before expensive lock is taken. */
1318         if (!lod->lod_qos.lq_dirty && lod->lod_qos.lq_same_space)
1319                 return 0;
1320
1321         if (lod->lod_desc.ld_active_tgt_count < 2)
1322                 return 0;
1323
1324         return 1;
1325 }
1326
1327 /**
1328  * Allocate a striping using an algorithm with weights.
1329  *
1330  * The function allocates OST objects to create a striping. The algorithm
1331  * used is based on weights (currently only using the free space), and it's
1332  * trying to ensure the space is used evenly by OSTs and OSSs. The striping
1333  * configuration (# of stripes, offset, pool) is taken from the object and
1334  * is prepared by the caller.
1335  *
1336  * If LOV_USES_DEFAULT_STRIPE is not passed and prepared configuration can't
1337  * be met due to too few OSTs, then allocation fails. If the flag is passed
1338  * fewer than 3/4 of the requested number of stripes can be allocated, then
1339  * allocation fails.
1340  *
1341  * No concurrent allocation is allowed on the object and this must be ensured
1342  * by the caller. All the internal structures are protected by the function.
1343  *
1344  * The algorithm has two steps: find available OSTs and calculate their
1345  * weights, then select the OSTs with their weights used as the probability.
1346  * An OST with a higher weight is proportionately more likely to be selected
1347  * than one with a lower weight.
1348  *
1349  * \param[in] env       execution environment for this thread
1350  * \param[in] lo        LOD object
1351  * \param[out] stripe   striping created
1352  * \param[in] flags     0 or LOV_USES_DEFAULT_STRIPE
1353  * \param[in] th        transaction handle
1354  *
1355  * \retval 0            on success
1356  * \retval -EAGAIN      not enough OSTs are found for specified stripe count
1357  * \retval -EINVAL      requested OST index is invalid
1358  * \retval negative     errno on failure
1359  */
1360 static int lod_alloc_qos(const struct lu_env *env, struct lod_object *lo,
1361                          struct dt_object **stripe, int flags,
1362                          struct thandle *th)
1363 {
1364         struct lod_device   *m = lu2lod_dev(lo->ldo_obj.do_lu.lo_dev);
1365         struct obd_statfs   *sfs = &lod_env_info(env)->lti_osfs;
1366         struct lod_tgt_desc *ost;
1367         struct dt_object    *o;
1368         __u64                total_weight = 0;
1369         unsigned int         i;
1370         int                  rc = 0;
1371         __u32                nfound, good_osts;
1372         __u32                stripe_cnt = lo->ldo_stripenr;
1373         __u32                stripe_cnt_min;
1374         struct pool_desc    *pool = NULL;
1375         struct ost_pool    *osts;
1376         ENTRY;
1377
1378         stripe_cnt_min = min_stripe_count(stripe_cnt, flags);
1379         if (stripe_cnt_min < 1)
1380                 RETURN(-EINVAL);
1381
1382         if (lo->ldo_pool)
1383                 pool = lod_find_pool(m, lo->ldo_pool);
1384
1385         if (pool != NULL) {
1386                 down_read(&pool_tgt_rw_sem(pool));
1387                 osts = &(pool->pool_obds);
1388         } else {
1389                 osts = &(m->lod_pool_info);
1390         }
1391
1392         /* Detect -EAGAIN early, before expensive lock is taken. */
1393         if (!lod_qos_is_usable(m))
1394                 GOTO(out_nolock, rc = -EAGAIN);
1395
1396         /* Do actual allocation, use write lock here. */
1397         down_write(&m->lod_qos.lq_rw_sem);
1398
1399         /*
1400          * Check again, while we were sleeping on @lq_rw_sem things could
1401          * change.
1402          */
1403         if (!lod_qos_is_usable(m))
1404                 GOTO(out, rc = -EAGAIN);
1405
1406         rc = lod_qos_calc_ppo(m);
1407         if (rc)
1408                 GOTO(out, rc);
1409
1410         rc = lod_qos_ost_in_use_clear(env, lo->ldo_stripenr);
1411         if (rc)
1412                 GOTO(out, rc);
1413
1414         good_osts = 0;
1415         /* Find all the OSTs that are valid stripe candidates */
1416         for (i = 0; i < osts->op_count; i++) {
1417                 if (!cfs_bitmap_check(m->lod_ost_bitmap, osts->op_array[i]))
1418                         continue;
1419
1420                 rc = lod_statfs_and_check(env, m, osts->op_array[i], sfs);
1421                 if (rc) {
1422                         /* this OSP doesn't feel well */
1423                         continue;
1424                 }
1425
1426                 /*
1427                  * skip full devices
1428                  */
1429                 if (lod_qos_dev_is_full(sfs))
1430                         continue;
1431
1432                 /* Fail Check before osc_precreate() is called
1433                    so we can only 'fail' single OSC. */
1434                 if (OBD_FAIL_CHECK(OBD_FAIL_MDS_OSC_PRECREATE) &&
1435                                    osts->op_array[i] == 0)
1436                         continue;
1437
1438                 ost = OST_TGT(m,osts->op_array[i]);
1439                 ost->ltd_qos.ltq_usable = 1;
1440                 lod_qos_calc_weight(m, osts->op_array[i]);
1441                 total_weight += ost->ltd_qos.ltq_weight;
1442
1443                 good_osts++;
1444         }
1445
1446         QOS_DEBUG("found %d good osts\n", good_osts);
1447
1448         if (good_osts < stripe_cnt_min)
1449                 GOTO(out, rc = -EAGAIN);
1450
1451         /* We have enough osts */
1452         if (good_osts < stripe_cnt)
1453                 stripe_cnt = good_osts;
1454
1455         /* Find enough OSTs with weighted random allocation. */
1456         nfound = 0;
1457         while (nfound < stripe_cnt) {
1458                 __u64 rand, cur_weight;
1459
1460                 cur_weight = 0;
1461                 rc = -ENOSPC;
1462
1463                 if (total_weight) {
1464 #if BITS_PER_LONG == 32
1465                         rand = cfs_rand() % (unsigned)total_weight;
1466                         /* If total_weight > 32-bit, first generate the high
1467                          * 32 bits of the random number, then add in the low
1468                          * 32 bits (truncated to the upper limit, if needed) */
1469                         if (total_weight > 0xffffffffULL)
1470                                 rand = (__u64)(cfs_rand() %
1471                                         (unsigned)(total_weight >> 32)) << 32;
1472                         else
1473                                 rand = 0;
1474
1475                         if (rand == (total_weight & 0xffffffff00000000ULL))
1476                                 rand |= cfs_rand() % (unsigned)total_weight;
1477                         else
1478                                 rand |= cfs_rand();
1479
1480 #else
1481                         rand = ((__u64)cfs_rand() << 32 | cfs_rand()) %
1482                                 total_weight;
1483 #endif
1484                 } else {
1485                         rand = 0;
1486                 }
1487
1488                 /* On average, this will hit larger-weighted OSTs more often.
1489                  * 0-weight OSTs will always get used last (only when rand=0) */
1490                 for (i = 0; i < osts->op_count; i++) {
1491                         __u32 idx = osts->op_array[i];
1492
1493                         if (!cfs_bitmap_check(m->lod_ost_bitmap, idx))
1494                                 continue;
1495
1496                         ost = OST_TGT(m,idx);
1497
1498                         if (!ost->ltd_qos.ltq_usable)
1499                                 continue;
1500
1501                         cur_weight += ost->ltd_qos.ltq_weight;
1502                         QOS_DEBUG("stripe_cnt=%d nfound=%d cur_weight="LPU64
1503                                   " rand="LPU64" total_weight="LPU64"\n",
1504                                   stripe_cnt, nfound, cur_weight, rand,
1505                                   total_weight);
1506
1507                         if (cur_weight < rand)
1508                                 continue;
1509
1510                         QOS_DEBUG("stripe=%d to idx=%d\n", nfound, idx);
1511
1512                         /*
1513                          * do not put >1 objects on a single OST
1514                          */
1515                         if (lod_qos_is_ost_used(env, idx, nfound))
1516                                 continue;
1517                         lod_qos_ost_in_use(env, nfound, idx);
1518
1519                         o = lod_qos_declare_object_on(env, m, idx, th);
1520                         if (IS_ERR(o)) {
1521                                 QOS_DEBUG("can't declare object on #%u: %d\n",
1522                                           idx, (int) PTR_ERR(o));
1523                                 continue;
1524                         }
1525                         stripe[nfound++] = o;
1526                         lod_qos_used(m, osts, idx, &total_weight);
1527                         rc = 0;
1528                         break;
1529                 }
1530
1531                 if (rc) {
1532                         /* no OST found on this iteration, give up */
1533                         break;
1534                 }
1535         }
1536
1537         if (unlikely(nfound != stripe_cnt)) {
1538                 /*
1539                  * when the decision to use weighted algorithm was made
1540                  * we had enough appropriate OSPs, but this state can
1541                  * change anytime (no space on OST, broken connection, etc)
1542                  * so it's possible OSP won't be able to provide us with
1543                  * an object due to just changed state
1544                  */
1545                 LCONSOLE_INFO("wanted %d, found %d\n", stripe_cnt, nfound);
1546                 for (i = 0; i < nfound; i++) {
1547                         LASSERT(stripe[i] != NULL);
1548                         lu_object_put(env, &stripe[i]->do_lu);
1549                         stripe[i] = NULL;
1550                 }
1551
1552                 /* makes sense to rebalance next time */
1553                 m->lod_qos.lq_dirty = 1;
1554                 m->lod_qos.lq_same_space = 0;
1555
1556                 rc = -EAGAIN;
1557         }
1558
1559 out:
1560         up_write(&m->lod_qos.lq_rw_sem);
1561
1562 out_nolock:
1563         if (pool != NULL) {
1564                 up_read(&pool_tgt_rw_sem(pool));
1565                 /* put back ref got by lod_find_pool() */
1566                 lod_pool_putref(pool);
1567         }
1568
1569         RETURN(rc);
1570 }
1571
1572 /**
1573  * Find largest stripe count the caller can use.
1574  *
1575  * Find the maximal possible stripe count not greater than \a stripe_count.
1576  * Sometimes suggested stripecount can't be reached for a number of reasons:
1577  * lack of enough active OSTs or the backend does not support EAs that large.
1578  * If the passed one is 0, then the filesystem's default one is used.
1579  *
1580  * \param[in] lod       LOD device
1581  * \param[in] magic     the format if striping
1582  * \param[in] stripe_count      count the caller would like to use
1583  *
1584  * \retval              the maximum usable stripe count
1585  */
1586 static __u16 lod_get_stripecnt(struct lod_device *lod, __u32 magic,
1587                                __u16 stripe_count)
1588 {
1589         __u32 max_stripes = LOV_MAX_STRIPE_COUNT_OLD;
1590
1591         if (!stripe_count)
1592                 stripe_count = lod->lod_desc.ld_default_stripe_count;
1593         if (stripe_count > lod->lod_desc.ld_active_tgt_count)
1594                 stripe_count = lod->lod_desc.ld_active_tgt_count;
1595         if (!stripe_count)
1596                 stripe_count = 1;
1597
1598         /* stripe count is based on whether OSD can handle larger EA sizes */
1599         if (lod->lod_osd_max_easize > 0)
1600                 max_stripes = lov_mds_md_max_stripe_count(
1601                         lod->lod_osd_max_easize, magic);
1602
1603         return (stripe_count < max_stripes) ? stripe_count : max_stripes;
1604 }
1605
1606 /**
1607  * Create in-core respresentation for a fully-defined striping
1608  *
1609  * When the caller passes a fully-defined striping (i.e. everything including
1610  * OST object FIDs are defined), then we still need to instantiate LU-cache
1611  * with the objects representing the stripes defined. This function completes
1612  * that task.
1613  *
1614  * \param[in] env       execution environment for this thread
1615  * \param[in] mo        LOD object
1616  * \param[in] buf       buffer containing the striping
1617  *
1618  * \retval 0            on success
1619  * \retval negative     negated errno on error
1620  */
1621 static int lod_use_defined_striping(const struct lu_env *env,
1622                                     struct lod_object *mo,
1623                                     const struct lu_buf *buf)
1624 {
1625         struct lov_mds_md_v1   *v1 = buf->lb_buf;
1626         struct lov_mds_md_v3   *v3 = buf->lb_buf;
1627         struct lov_ost_data_v1 *objs;
1628         __u32                   magic;
1629         int                     rc = 0;
1630         ENTRY;
1631
1632         magic = le32_to_cpu(v1->lmm_magic);
1633         if (magic == LOV_MAGIC_V1_DEF) {
1634                 magic = LOV_MAGIC_V1;
1635                 objs = &v1->lmm_objects[0];
1636         } else if (magic == LOV_MAGIC_V3_DEF) {
1637                 magic = LOV_MAGIC_V3;
1638                 objs = &v3->lmm_objects[0];
1639                 lod_object_set_pool(mo, v3->lmm_pool_name);
1640         } else {
1641                 GOTO(out, rc = -EINVAL);
1642         }
1643
1644         mo->ldo_pattern = le32_to_cpu(v1->lmm_pattern);
1645         mo->ldo_stripe_size = le32_to_cpu(v1->lmm_stripe_size);
1646         mo->ldo_stripenr = le16_to_cpu(v1->lmm_stripe_count);
1647         mo->ldo_layout_gen = le16_to_cpu(v1->lmm_layout_gen);
1648
1649         /* fixup for released file before object initialization */
1650         if (mo->ldo_pattern & LOV_PATTERN_F_RELEASED) {
1651                 mo->ldo_released_stripenr = mo->ldo_stripenr;
1652                 mo->ldo_stripenr = 0;
1653         }
1654
1655         LASSERT(buf->lb_len >= lov_mds_md_size(mo->ldo_stripenr, magic));
1656
1657         if (mo->ldo_stripenr > 0)
1658                 rc = lod_initialize_objects(env, mo, objs);
1659
1660 out:
1661         RETURN(rc);
1662 }
1663
1664 /**
1665  * Parse suggested striping configuration.
1666  *
1667  * The caller gets a suggested striping configuration from a number of sources
1668  * including per-directory default and applications. Then it needs to verify
1669  * the suggested striping is valid, apply missing bits and store the resulting
1670  * configuration in the object to be used by the allocator later. Must not be
1671  * called concurrently against the same object. It's OK to provide a
1672  * fully-defined striping.
1673  *
1674  * \param[in] env       execution environment for this thread
1675  * \param[in] lo        LOD object
1676  * \param[in] buf       buffer containing the striping
1677  *
1678  * \retval 0            on success
1679  * \retval negative     negated errno on error
1680  */
1681 static int lod_qos_parse_config(const struct lu_env *env,
1682                                 struct lod_object *lo,
1683                                 const struct lu_buf *buf)
1684 {
1685         struct lod_device     *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1686         struct lov_user_md_v1 *v1 = NULL;
1687         struct lov_user_md_v3 *v3 = NULL;
1688         char                  *pool_name = NULL;
1689         __u32                  magic;
1690         int                    rc;
1691         unsigned int           size;
1692         ENTRY;
1693
1694         if (buf == NULL || buf->lb_buf == NULL || buf->lb_len == 0)
1695                 RETURN(0);
1696
1697         v3 = buf->lb_buf;
1698         v1 = buf->lb_buf;
1699         magic = v1->lmm_magic;
1700
1701         if (unlikely(magic == LOV_MAGIC_V1_DEF || magic == LOV_MAGIC_V3_DEF)) {
1702                 /* try to use as fully defined striping */
1703                 rc = lod_use_defined_striping(env, lo, buf);
1704                 RETURN(rc);
1705         }
1706
1707         switch (magic) {
1708         case __swab32(LOV_USER_MAGIC_V1):
1709                 lustre_swab_lov_user_md_v1(v1);
1710                 magic = v1->lmm_magic;
1711                 /* fall through */
1712         case LOV_USER_MAGIC_V1:
1713                 size = sizeof(*v1);
1714                 break;
1715
1716         case __swab32(LOV_USER_MAGIC_V3):
1717                 lustre_swab_lov_user_md_v3(v3);
1718                 magic = v3->lmm_magic;
1719                 /* fall through */
1720         case LOV_USER_MAGIC_V3:
1721                 size = sizeof(*v3);
1722                 pool_name = v3->lmm_pool_name;
1723                 break;
1724
1725         case __swab32(LOV_USER_MAGIC_SPECIFIC):
1726                 lustre_swab_lov_user_md_v3(v3);
1727                 lustre_swab_lov_user_md_objects(v3->lmm_objects,
1728                                                 v3->lmm_stripe_count);
1729                 magic = v3->lmm_magic;
1730                 /* fall through */
1731         case LOV_USER_MAGIC_SPECIFIC:
1732                 if (v3->lmm_stripe_offset == LOV_OFFSET_DEFAULT)
1733                         v3->lmm_stripe_offset = v3->lmm_objects[0].l_ost_idx;
1734                 if (v3->lmm_pool_name[0] != '\0')
1735                         pool_name = v3->lmm_pool_name;
1736                 size = lov_user_md_size(v3->lmm_stripe_count,
1737                                         LOV_USER_MAGIC_SPECIFIC);
1738                 break;
1739
1740         default:
1741                 CERROR("%s: unrecognized magic %X\n",
1742                        lod2obd(d)->obd_name, magic);
1743                 RETURN(-EINVAL);
1744         }
1745
1746         if (unlikely(buf->lb_len < size)) {
1747                 CERROR("%s: wrong size: %zd, expect: %u\n",
1748                        lod2obd(d)->obd_name, buf->lb_len, size);
1749                 RETURN(-EINVAL);
1750         }
1751
1752         lustre_print_user_md(D_OTHER, v1, "parse config");
1753
1754         v1->lmm_magic = magic;
1755         if (v1->lmm_pattern == 0)
1756                 v1->lmm_pattern = LOV_PATTERN_RAID0;
1757         if (lov_pattern(v1->lmm_pattern) != LOV_PATTERN_RAID0) {
1758                 CERROR("%s: invalid pattern: %x\n",
1759                        lod2obd(d)->obd_name, v1->lmm_pattern);
1760                 RETURN(-EINVAL);
1761         }
1762         lo->ldo_pattern = v1->lmm_pattern;
1763
1764         if (v1->lmm_stripe_size > 0)
1765                 lo->ldo_stripe_size = v1->lmm_stripe_size;
1766
1767         if (lo->ldo_stripe_size & (LOV_MIN_STRIPE_SIZE - 1))
1768                 lo->ldo_stripe_size = LOV_MIN_STRIPE_SIZE;
1769
1770         if (v1->lmm_stripe_count > 0)
1771                 lo->ldo_stripenr = v1->lmm_stripe_count;
1772
1773         lo->ldo_def_stripe_offset = v1->lmm_stripe_offset;
1774
1775         lod_object_set_pool(lo, NULL);
1776         if (pool_name != NULL) {
1777                 struct pool_desc *pool;
1778
1779                 /* In the function below, .hs_keycmp resolves to
1780                  * pool_hashkey_keycmp() */
1781                 /* coverity[overrun-buffer-val] */
1782                 pool = lod_find_pool(d, pool_name);
1783                 if (pool != NULL) {
1784                         if (lo->ldo_def_stripe_offset != LOV_OFFSET_DEFAULT) {
1785                                 rc = lod_check_index_in_pool(
1786                                                lo->ldo_def_stripe_offset, pool);
1787                                 if (rc < 0) {
1788                                         lod_pool_putref(pool);
1789                                         CERROR("%s: invalid offset, %u\n",
1790                                                lod2obd(d)->obd_name,
1791                                                lo->ldo_def_stripe_offset);
1792                                         RETURN(-EINVAL);
1793                                 }
1794                         }
1795
1796                         if (lo->ldo_stripenr > pool_tgt_count(pool))
1797                                 lo->ldo_stripenr = pool_tgt_count(pool);
1798
1799                         lod_pool_putref(pool);
1800                 }
1801
1802                 lod_object_set_pool(lo, pool_name);
1803         }
1804
1805         /* fixup for released file */
1806         if (lo->ldo_pattern & LOV_PATTERN_F_RELEASED) {
1807                 lo->ldo_released_stripenr = lo->ldo_stripenr;
1808                 lo->ldo_stripenr = 0;
1809         }
1810
1811         RETURN(0);
1812 }
1813
1814 /**
1815  * Create a striping for an obejct.
1816  *
1817  * The function creates a new striping for the object. A buffer containing
1818  * configuration hints can be provided optionally. The function tries QoS
1819  * algorithm first unless free space is distributed evenly among OSTs, but
1820  * by default RR algorithm is preferred due to internal concurrency (QoS is
1821  * serialized). The caller must ensure no concurrent calls to the function
1822  * are made against the same object.
1823  *
1824  * \param[in] env       execution environment for this thread
1825  * \param[in] lo        LOD object
1826  * \param[in] attr      attributes OST objects will be declared with
1827  * \param[in] buf       suggested striping configuration or NULL
1828  * \param[in] th        transaction handle
1829  *
1830  * \retval 0            on success
1831  * \retval negative     negated errno on error
1832  */
1833 int lod_qos_prep_create(const struct lu_env *env, struct lod_object *lo,
1834                         struct lu_attr *attr, const struct lu_buf *buf,
1835                         struct thandle *th)
1836 {
1837         struct lod_device      *d = lu2lod_dev(lod2lu_obj(lo)->lo_dev);
1838         struct dt_object      **stripe;
1839         int                     stripe_len;
1840         int                     flag = LOV_USES_ASSIGNED_STRIPE;
1841         int                     i, rc;
1842         ENTRY;
1843
1844         LASSERT(lo);
1845
1846         /* no OST available */
1847         /* XXX: should we be waiting a bit to prevent failures during
1848          * cluster initialization? */
1849         if (d->lod_ostnr == 0)
1850                 GOTO(out, rc = -EIO);
1851
1852         /*
1853          * by this time, the object's ldo_stripenr and ldo_stripe_size
1854          * contain default value for striping: taken from the parent
1855          * or from filesystem defaults
1856          *
1857          * in case the caller is passing lovea with new striping config,
1858          * we may need to parse lovea and apply new configuration
1859          */
1860         rc = lod_qos_parse_config(env, lo, buf);
1861         if (rc)
1862                 GOTO(out, rc);
1863
1864         /* A released file is being created */
1865         if (lo->ldo_stripenr == 0)
1866                 GOTO(out, rc = 0);
1867
1868         if (likely(lo->ldo_stripe == NULL)) {
1869                 struct lov_user_md *lum = NULL;
1870
1871                 /*
1872                  * no striping has been created so far
1873                  */
1874                 LASSERT(lo->ldo_stripenr > 0);
1875                 /*
1876                  * statfs and check OST targets now, since ld_active_tgt_count
1877                  * could be changed if some OSTs are [de]activated manually.
1878                  */
1879                 lod_qos_statfs_update(env, d);
1880                 lo->ldo_stripenr = lod_get_stripecnt(d, LOV_MAGIC,
1881                                                      lo->ldo_stripenr);
1882
1883                 stripe_len = lo->ldo_stripenr;
1884                 OBD_ALLOC(stripe, sizeof(stripe[0]) * stripe_len);
1885                 if (stripe == NULL)
1886                         GOTO(out, rc = -ENOMEM);
1887
1888                 lod_getref(&d->lod_ost_descs);
1889                 /* XXX: support for non-0 files w/o objects */
1890                 CDEBUG(D_OTHER, "tgt_count %d stripenr %d\n",
1891                                 d->lod_desc.ld_tgt_count, stripe_len);
1892
1893                 if (buf != NULL && buf->lb_buf != NULL)
1894                         lum = buf->lb_buf;
1895
1896                 if (lum != NULL && lum->lmm_magic == LOV_USER_MAGIC_SPECIFIC) {
1897                         rc = lod_alloc_ost_list(env, lo, stripe, lum, th);
1898                 } else if (lo->ldo_def_stripe_offset == LOV_OFFSET_DEFAULT) {
1899                         rc = lod_alloc_qos(env, lo, stripe, flag, th);
1900                         if (rc == -EAGAIN)
1901                                 rc = lod_alloc_rr(env, lo, stripe, flag, th);
1902                 } else {
1903                         rc = lod_alloc_specific(env, lo, stripe, flag, th);
1904                 }
1905                 lod_putref(d, &d->lod_ost_descs);
1906
1907                 if (rc < 0) {
1908                         for (i = 0; i < stripe_len; i++)
1909                                 if (stripe[i] != NULL)
1910                                         lu_object_put(env, &stripe[i]->do_lu);
1911
1912                         OBD_FREE(stripe, sizeof(stripe[0]) * stripe_len);
1913                         lo->ldo_stripenr = 0;
1914                 } else {
1915                         lo->ldo_stripe = stripe;
1916                         lo->ldo_stripes_allocated = stripe_len;
1917                 }
1918         } else {
1919                 /*
1920                  * lod_qos_parse_config() found supplied buf as a predefined
1921                  * striping (not a hint), so it allocated all the object
1922                  * now we need to create them
1923                  */
1924                 for (i = 0; i < lo->ldo_stripenr; i++) {
1925                         struct dt_object  *o;
1926
1927                         o = lo->ldo_stripe[i];
1928                         LASSERT(o);
1929
1930                         rc = lod_sub_object_declare_create(env, o, attr, NULL,
1931                                                            NULL, th);
1932                         if (rc < 0) {
1933                                 CERROR("can't declare create: %d\n", rc);
1934                                 break;
1935                         }
1936                 }
1937         }
1938
1939 out:
1940         RETURN(rc);
1941 }
1942