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