Whamcloud - gitweb
a1fc6b01f194001947310401e9c36ad289a0586d
[fs/lustre-release.git] / lustre / mdt / mdt_coordinator.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 (c) 2011, 2012 Commissariat a l'energie atomique et aux energies
24  *                          alternatives
25  *
26  * Copyright (c) 2013, 2017, Intel Corporation.
27  * Use is subject to license terms.
28  */
29 /*
30  * lustre/mdt/mdt_coordinator.c
31  *
32  * Lustre HSM Coordinator
33  *
34  * Author: Jacques-Charles Lafoucriere <jacques-charles.lafoucriere@cea.fr>
35  * Author: Aurelien Degremont <aurelien.degremont@cea.fr>
36  * Author: Thomas Leibovici <thomas.leibovici@cea.fr>
37  */
38
39 #define DEBUG_SUBSYSTEM S_MDS
40
41 #include <linux/kthread.h>
42 #include <obd_support.h>
43 #include <lustre_export.h>
44 #include <obd.h>
45 #include <lprocfs_status.h>
46 #include <lustre_log.h>
47 #include <lustre_kernelcomm.h>
48 #include "mdt_internal.h"
49
50 /**
51  * get obj and HSM attributes on a fid
52  * \param mti [IN] context
53  * \param fid [IN] object fid
54  * \param hsm [OUT] HSM meta data
55  * \retval obj or error (-ENOENT if not found)
56  */
57 struct mdt_object *mdt_hsm_get_md_hsm(struct mdt_thread_info *mti,
58                                       const struct lu_fid *fid,
59                                       struct md_hsm *hsm)
60 {
61         struct md_attr          *ma;
62         struct mdt_object       *obj;
63         int                      rc;
64         ENTRY;
65
66         ma = &mti->mti_attr;
67         ma->ma_need = MA_HSM;
68         ma->ma_valid = 0;
69
70         /* find object by FID */
71         obj = mdt_object_find(mti->mti_env, mti->mti_mdt, fid);
72         if (IS_ERR(obj))
73                 RETURN(obj);
74
75         if (!mdt_object_exists(obj)) {
76                 /* no more object */
77                 mdt_object_put(mti->mti_env, obj);
78                 RETURN(ERR_PTR(-ENOENT));
79         }
80
81         rc = mdt_attr_get_complex(mti, obj, ma);
82         if (rc) {
83                 mdt_object_put(mti->mti_env, obj);
84                 RETURN(ERR_PTR(rc));
85         }
86
87         if (ma->ma_valid & MA_HSM)
88                 *hsm = ma->ma_hsm;
89         else
90                 memset(hsm, 0, sizeof(*hsm));
91         ma->ma_valid = 0;
92         RETURN(obj);
93 }
94
95 void mdt_hsm_dump_hal(int level, const char *prefix,
96                       struct hsm_action_list *hal)
97 {
98         int                      i, sz;
99         struct hsm_action_item  *hai;
100         char                     buf[12];
101
102         CDEBUG(level, "%s: HAL header: version %X count %d"
103                       " archive_id %d flags %#llx\n",
104                prefix, hal->hal_version, hal->hal_count,
105                hal->hal_archive_id, hal->hal_flags);
106
107         hai = hai_first(hal);
108         for (i = 0; i < hal->hal_count; i++) {
109                 sz = hai->hai_len - sizeof(*hai);
110                 CDEBUG(level, "%s %d: fid="DFID" dfid="DFID
111                        " cookie=%#llx"
112                        " action=%s extent=%#llx-%#llx gid=%#llx"
113                        " datalen=%d data=[%s]\n",
114                        prefix, i,
115                        PFID(&hai->hai_fid), PFID(&hai->hai_dfid),
116                        hai->hai_cookie,
117                        hsm_copytool_action2name(hai->hai_action),
118                        hai->hai_extent.offset,
119                        hai->hai_extent.length,
120                        hai->hai_gid, sz,
121                        hai_dump_data_field(hai, buf, sizeof(buf)));
122                 hai = hai_next(hai);
123         }
124 }
125
126 /**
127  * data passed to llog_cat_process() callback
128  * to scan requests and take actions
129  */
130 struct hsm_scan_request {
131         int                      hal_sz;
132         int                      hal_used_sz;
133         struct hsm_action_list  *hal;
134 };
135
136 struct hsm_scan_data {
137         struct mdt_thread_info  *hsd_mti;
138         char                     hsd_fsname[MTI_NAME_MAXLEN + 1];
139         /* are we scanning the logs for housekeeping, or just looking
140          * for new work?
141          */
142         bool                     hsd_housekeeping;
143         bool                     hsd_one_restore;
144         u32                      hsd_start_cat_idx;
145         u32                      hsd_start_rec_idx;
146         int                      hsd_action_count;
147         int                      hsd_request_len; /* array alloc len */
148         int                      hsd_request_count; /* array used count */
149         struct hsm_scan_request *hsd_request;
150 };
151
152 static int mdt_cdt_waiting_cb(const struct lu_env *env,
153                               struct mdt_device *mdt,
154                               struct llog_handle *llh,
155                               struct llog_agent_req_rec *larr,
156                               struct hsm_scan_data *hsd)
157 {
158         struct coordinator *cdt = &mdt->mdt_coordinator;
159         struct hsm_scan_request *request;
160         struct hsm_action_item *hai;
161         size_t hai_size;
162         u32 archive_id;
163         bool wrapped;
164         int i;
165
166         /* Are agents full? */
167         if (atomic_read(&cdt->cdt_request_count) >= cdt->cdt_max_requests)
168                 RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
169
170         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
171             cdt->cdt_max_requests) {
172                 /* We cannot send any more request
173                  *
174                  *                     *** SPECIAL CASE ***
175                  *
176                  * Restore requests are too important not to schedule at least
177                  * one, everytime we can.
178                  */
179                 if (larr->arr_hai.hai_action != HSMA_RESTORE ||
180                     hsd->hsd_one_restore)
181                         RETURN(hsd->hsd_housekeeping ? 0 : LLOG_PROC_BREAK);
182         }
183
184         hai_size = cfs_size_round(larr->arr_hai.hai_len);
185         archive_id = larr->arr_archive_id;
186
187         /* Can we add this action to one of the existing HALs in hsd. */
188         request = NULL;
189         for (i = 0; i < hsd->hsd_request_count; i++) {
190                 if (hsd->hsd_request[i].hal->hal_archive_id == archive_id &&
191                     hsd->hsd_request[i].hal_used_sz + hai_size <=
192                     LDLM_MAXREQSIZE) {
193                         request = &hsd->hsd_request[i];
194                         break;
195                 }
196         }
197
198         /* Are we trying to force-schedule a request? */
199         if (hsd->hsd_action_count + atomic_read(&cdt->cdt_request_count) >=
200             cdt->cdt_max_requests) {
201                 /* Is there really no compatible hsm_scan_request? */
202                 if (!request) {
203                         for (i -= 1; i >= 0; i--) {
204                                 if (hsd->hsd_request[i].hal->hal_archive_id ==
205                                     archive_id) {
206                                         request = &hsd->hsd_request[i];
207                                         break;
208                                 }
209                         }
210                 }
211
212                 /* Make room for the hai */
213                 if (request) {
214                         /* Discard the last hai until there is enough space */
215                         do {
216                                 request->hal->hal_count--;
217
218                                 hai = hai_first(request->hal);
219                                 for (i = 0; i < request->hal->hal_count; i++)
220                                         hai = hai_next(hai);
221                                 request->hal_used_sz -=
222                                         cfs_size_round(hai->hai_len);
223                                 hsd->hsd_action_count--;
224                         } while (request->hal_used_sz + hai_size >
225                                  LDLM_MAXREQSIZE);
226                 } else if (hsd->hsd_housekeeping) {
227                         struct hsm_scan_request *tmp;
228
229                         /* Discard the (whole) last hal */
230                         hsd->hsd_request_count--;
231                         LASSERT(hsd->hsd_request_count >= 0);
232                         tmp = &hsd->hsd_request[hsd->hsd_request_count];
233                         hsd->hsd_action_count -= tmp->hal->hal_count;
234                         LASSERT(hsd->hsd_action_count >= 0);
235                         OBD_FREE(tmp->hal, tmp->hal_sz);
236                 } else {
237                         /* Bailing out, this code path is too hot */
238                         RETURN(LLOG_PROC_BREAK);
239
240                 }
241         }
242
243         if (!request) {
244                 struct hsm_action_list *hal;
245
246                 LASSERT(hsd->hsd_request_count < hsd->hsd_request_len);
247                 request = &hsd->hsd_request[hsd->hsd_request_count];
248
249                 /* allocates hai vector size just needs to be large
250                  * enough */
251                 request->hal_sz = sizeof(*request->hal) +
252                         cfs_size_round(MTI_NAME_MAXLEN + 1) + 2 * hai_size;
253                 OBD_ALLOC_LARGE(hal, request->hal_sz);
254                 if (!hal)
255                         RETURN(-ENOMEM);
256
257                 hal->hal_version = HAL_VERSION;
258                 strlcpy(hal->hal_fsname, hsd->hsd_fsname, MTI_NAME_MAXLEN + 1);
259                 hal->hal_archive_id = larr->arr_archive_id;
260                 hal->hal_flags = larr->arr_flags;
261                 hal->hal_count = 0;
262                 request->hal_used_sz = hal_size(hal);
263                 request->hal = hal;
264                 hsd->hsd_request_count++;
265         } else if (request->hal_sz < request->hal_used_sz + hai_size) {
266                 /* Not enough room, need an extension */
267                 void *hal_buffer;
268                 int sz;
269
270                 sz = min_t(int, 2 * request->hal_sz, LDLM_MAXREQSIZE);
271                 LASSERT(request->hal_used_sz + hai_size < sz);
272
273                 OBD_ALLOC_LARGE(hal_buffer, sz);
274                 if (!hal_buffer)
275                         RETURN(-ENOMEM);
276
277                 memcpy(hal_buffer, request->hal, request->hal_used_sz);
278                 OBD_FREE_LARGE(request->hal, request->hal_sz);
279                 request->hal = hal_buffer;
280                 request->hal_sz = sz;
281         }
282
283         hai = hai_first(request->hal);
284         for (i = 0; i < request->hal->hal_count; i++)
285                 hai = hai_next(hai);
286
287         memcpy(hai, &larr->arr_hai, larr->arr_hai.hai_len);
288
289         request->hal_used_sz += hai_size;
290         request->hal->hal_count++;
291
292         hsd->hsd_action_count++;
293
294         switch (hai->hai_action) {
295         case HSMA_CANCEL:
296                 break;
297         case HSMA_RESTORE:
298                 hsd->hsd_one_restore = true;
299                 /* Intentional fallthrough */
300         default:
301                 cdt_agent_record_hash_add(cdt, hai->hai_cookie,
302                                           llh->lgh_hdr->llh_cat_idx,
303                                           larr->arr_hdr.lrh_index);
304         }
305
306         wrapped = llh->lgh_hdr->llh_cat_idx >= llh->lgh_last_idx &&
307                   llh->lgh_hdr->llh_count > 1;
308         if ((!wrapped && llh->lgh_hdr->llh_cat_idx > hsd->hsd_start_cat_idx) ||
309             (wrapped && llh->lgh_hdr->llh_cat_idx < hsd->hsd_start_cat_idx) ||
310             (llh->lgh_hdr->llh_cat_idx == hsd->hsd_start_cat_idx &&
311              larr->arr_hdr.lrh_index > hsd->hsd_start_rec_idx)) {
312                 hsd->hsd_start_cat_idx = llh->lgh_hdr->llh_cat_idx;
313                 hsd->hsd_start_rec_idx = larr->arr_hdr.lrh_index;
314         }
315
316         RETURN(0);
317 }
318
319 static int mdt_cdt_started_cb(const struct lu_env *env,
320                               struct mdt_device *mdt,
321                               struct llog_handle *llh,
322                               struct llog_agent_req_rec *larr,
323                               struct hsm_scan_data *hsd)
324 {
325         struct coordinator *cdt = &mdt->mdt_coordinator;
326         struct hsm_action_item *hai = &larr->arr_hai;
327         struct cdt_agent_req *car;
328         time64_t now = ktime_get_real_seconds();
329         time64_t last;
330         enum changelog_rec_flags clf_flags;
331         int rc;
332
333         if (!hsd->hsd_housekeeping)
334                 RETURN(0);
335
336         /* we search for a running request
337          * error may happen if coordinator crashes or stopped
338          * with running request
339          */
340         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
341         if (car == NULL) {
342                 last = larr->arr_req_change;
343         } else {
344                 last = car->car_req_update;
345         }
346
347         /* test if request too long, if yes cancel it
348          * the same way the copy tool acknowledge a cancel request */
349         if (now <= last + cdt->cdt_active_req_timeout)
350                 GOTO(out_car, rc = 0);
351
352         dump_llog_agent_req_rec("request timed out, start cleaning", larr);
353
354         if (car != NULL) {
355                 car->car_req_update = now;
356                 mdt_hsm_agent_update_statistics(cdt, 0, 1, 0, &car->car_uuid);
357                 /* Remove car from memory list (LU-9075) */
358                 mdt_cdt_remove_request(cdt, hai->hai_cookie);
359         }
360
361         /* Emit a changelog record for the failed action.*/
362         clf_flags = 0;
363         hsm_set_cl_error(&clf_flags, ECANCELED);
364
365         switch (hai->hai_action) {
366         case HSMA_ARCHIVE:
367                 hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
368                 break;
369         case HSMA_RESTORE:
370                 hsm_set_cl_event(&clf_flags, HE_RESTORE);
371                 break;
372         case HSMA_REMOVE:
373                 hsm_set_cl_event(&clf_flags, HE_REMOVE);
374                 break;
375         case HSMA_CANCEL:
376                 hsm_set_cl_event(&clf_flags, HE_CANCEL);
377                 break;
378         default:
379                 /* Unknown record type, skip changelog. */
380                 clf_flags = 0;
381                 break;
382         }
383
384         if (clf_flags != 0)
385                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
386                              &hai->hai_fid);
387
388         if (hai->hai_action == HSMA_RESTORE)
389                 cdt_restore_handle_del(hsd->hsd_mti, cdt, &hai->hai_fid);
390
391         larr->arr_status = ARS_CANCELED;
392         larr->arr_req_change = now;
393         rc = llog_write(hsd->hsd_mti->mti_env, llh, &larr->arr_hdr,
394                         larr->arr_hdr.lrh_index);
395         if (rc < 0) {
396                 CERROR("%s: cannot update agent log: rc = %d\n",
397                        mdt_obd_name(mdt), rc);
398                 rc = LLOG_DEL_RECORD;
399         }
400
401         /* ct has completed a request, so a slot is available,
402          * signal the coordinator to find new work */
403         mdt_hsm_cdt_event(cdt);
404 out_car:
405         if (car != NULL)
406                 mdt_cdt_put_request(car);
407
408         RETURN(rc);
409 }
410
411 /**
412  *  llog_cat_process() callback, used to:
413  *  - find waiting request and start action
414  *  - purge canceled and done requests
415  * \param env [IN] environment
416  * \param llh [IN] llog handle
417  * \param hdr [IN] llog record
418  * \param data [IN/OUT] cb data = struct hsm_scan_data
419  * \retval 0 success
420  * \retval -ve failure
421  */
422 static int mdt_coordinator_cb(const struct lu_env *env,
423                               struct llog_handle *llh,
424                               struct llog_rec_hdr *hdr,
425                               void *data)
426 {
427         struct llog_agent_req_rec *larr = (struct llog_agent_req_rec *)hdr;
428         struct hsm_scan_data *hsd = data;
429         struct mdt_device *mdt = hsd->hsd_mti->mti_mdt;
430         struct coordinator *cdt = &mdt->mdt_coordinator;
431         ENTRY;
432
433         larr = (struct llog_agent_req_rec *)hdr;
434         dump_llog_agent_req_rec("mdt_coordinator_cb(): ", larr);
435         switch (larr->arr_status) {
436         case ARS_WAITING:
437                 RETURN(mdt_cdt_waiting_cb(env, mdt, llh, larr, hsd));
438         case ARS_STARTED:
439                 RETURN(mdt_cdt_started_cb(env, mdt, llh, larr, hsd));
440         default:
441                 if (!hsd->hsd_housekeeping)
442                         RETURN(0);
443
444                 if ((larr->arr_req_change + cdt->cdt_grace_delay) <
445                     ktime_get_real_seconds()) {
446                         cdt_agent_record_hash_del(cdt,
447                                                   larr->arr_hai.hai_cookie);
448                         RETURN(LLOG_DEL_RECORD);
449                 }
450
451                 RETURN(0);
452         }
453 }
454
455 /* Release the ressource used by the coordinator. Called when the
456  * coordinator is stopping. */
457 static void mdt_hsm_cdt_cleanup(struct mdt_device *mdt)
458 {
459         struct coordinator              *cdt = &mdt->mdt_coordinator;
460         struct cdt_agent_req            *car, *tmp1;
461         struct hsm_agent                *ha, *tmp2;
462         struct cdt_restore_handle       *crh, *tmp3;
463         struct mdt_thread_info          *cdt_mti;
464
465         /* start cleaning */
466         down_write(&cdt->cdt_request_lock);
467         list_for_each_entry_safe(car, tmp1, &cdt->cdt_request_list,
468                                  car_request_list) {
469                 cfs_hash_del(cdt->cdt_request_cookie_hash,
470                              &car->car_hai->hai_cookie,
471                              &car->car_cookie_hash);
472                 list_del(&car->car_request_list);
473                 mdt_cdt_put_request(car);
474         }
475         up_write(&cdt->cdt_request_lock);
476
477         down_write(&cdt->cdt_agent_lock);
478         list_for_each_entry_safe(ha, tmp2, &cdt->cdt_agents, ha_list) {
479                 list_del(&ha->ha_list);
480                 if (ha->ha_archive_cnt != 0)
481                         OBD_FREE_PTR_ARRAY(ha->ha_archive_id,
482                                            ha->ha_archive_cnt);
483                 OBD_FREE_PTR(ha);
484         }
485         up_write(&cdt->cdt_agent_lock);
486
487         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
488         mutex_lock(&cdt->cdt_restore_lock);
489         list_for_each_entry_safe(crh, tmp3, &cdt->cdt_restore_handle_list,
490                                  crh_list) {
491                 list_del(&crh->crh_list);
492                 /* give back layout lock */
493                 mdt_object_unlock(cdt_mti, NULL, &crh->crh_lh, 1);
494                 OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
495         }
496         mutex_unlock(&cdt->cdt_restore_lock);
497 }
498
499 /*
500  * Coordinator state transition table, indexed on enum cdt_states, taking
501  * from and to states. For instance since CDT_INIT to CDT_RUNNING is a
502  * valid transition, cdt_transition[CDT_INIT][CDT_RUNNING] is true.
503  */
504 static bool cdt_transition[CDT_STATES_COUNT][CDT_STATES_COUNT] = {
505         /* from -> to:    stopped init   running disable stopping */
506         /* stopped */   { true,   true,  false,  false,  false },
507         /* init */      { true,   false, true,   false,  false },
508         /* running */   { false,  false, true,   true,   true },
509         /* disable */   { false,  false, true,   true,   true },
510         /* stopping */  { true,   false, false,  false,  false }
511 };
512
513 /**
514  * Change coordinator thread state
515  * Some combinations are not valid, so catch them here.
516  *
517  * Returns 0 on success, with old_state set if not NULL, or -EINVAL if
518  * the transition was not possible.
519  */
520 static int set_cdt_state_locked(struct coordinator *cdt,
521                                 enum cdt_states new_state)
522 {
523         int rc;
524         enum cdt_states state;
525
526         state = cdt->cdt_state;
527
528         if (cdt_transition[state][new_state]) {
529                 cdt->cdt_state = new_state;
530                 rc = 0;
531         } else {
532                 CDEBUG(D_HSM,
533                        "unexpected coordinator transition, from=%s, to=%s\n",
534                        cdt_mdt_state2str(state), cdt_mdt_state2str(new_state));
535                 rc = -EINVAL;
536         }
537
538         return rc;
539 }
540
541 static int set_cdt_state(struct coordinator *cdt, enum cdt_states new_state)
542 {
543         int rc;
544
545         mutex_lock(&cdt->cdt_state_lock);
546         rc = set_cdt_state_locked(cdt, new_state);
547         mutex_unlock(&cdt->cdt_state_lock);
548
549         return rc;
550 }
551
552
553
554 /**
555  * coordinator thread
556  * \param data [IN] obd device
557  * \retval 0 success
558  * \retval -ve failure
559  */
560 static int mdt_coordinator(void *data)
561 {
562         struct mdt_thread_info  *mti = data;
563         struct mdt_device       *mdt = mti->mti_mdt;
564         struct coordinator      *cdt = &mdt->mdt_coordinator;
565         struct hsm_scan_data     hsd = { NULL };
566         time64_t                 last_housekeeping = 0;
567         size_t request_sz = 0;
568         int rc;
569         ENTRY;
570
571         CDEBUG(D_HSM, "%s: coordinator thread starting, pid=%d\n",
572                mdt_obd_name(mdt), current->pid);
573
574         hsd.hsd_mti = mti;
575         obd_uuid2fsname(hsd.hsd_fsname, mdt_obd_name(mdt),
576                         sizeof(hsd.hsd_fsname));
577
578         set_cdt_state(cdt, CDT_RUNNING);
579
580         /* Inform mdt_hsm_cdt_start(). */
581         wake_up(&cdt->cdt_waitq);
582
583         while (1) {
584                 int i;
585                 int update_idx = 0;
586                 int updates_sz;
587                 int updates_cnt;
588                 u32 start_cat_idx;
589                 u32 start_rec_idx;
590                 struct hsm_record_update *updates;
591
592                 /* Limit execution of the expensive requests traversal
593                  * to at most one second. This prevents repeatedly
594                  * locking/unlocking the catalog for each request
595                  * and preventing other HSM operations from happening
596                  */
597                 wait_event_interruptible_timeout(cdt->cdt_waitq,
598                                                  kthread_should_stop() ||
599                                                  cdt->cdt_wakeup_coordinator,
600                                                  cfs_time_seconds(1));
601
602                 cdt->cdt_wakeup_coordinator = false;
603                 CDEBUG(D_HSM, "coordinator resumes\n");
604
605                 if (kthread_should_stop()) {
606                         CDEBUG(D_HSM, "Coordinator stops\n");
607                         rc = 0;
608                         break;
609                 }
610
611                 /* if coordinator is suspended continue to wait */
612                 if (cdt->cdt_state == CDT_DISABLE) {
613                         CDEBUG(D_HSM, "disable state, coordinator sleeps\n");
614                         continue;
615                 }
616
617                 /* If no event, and no housekeeping to do, continue to
618                  * wait. */
619                 if (last_housekeeping + cdt->cdt_loop_period <=
620                     ktime_get_real_seconds()) {
621                         last_housekeeping = ktime_get_real_seconds();
622                         hsd.hsd_housekeeping = true;
623                         start_cat_idx = 0;
624                         start_rec_idx = 0;
625                 } else if (cdt->cdt_event) {
626                         hsd.hsd_housekeeping = false;
627                         start_cat_idx = hsd.hsd_start_cat_idx;
628                         start_rec_idx = hsd.hsd_start_rec_idx;
629                 } else {
630                         continue;
631                 }
632
633                 cdt->cdt_event = false;
634
635                 CDEBUG(D_HSM, "coordinator starts reading llog\n");
636
637                 if (hsd.hsd_request_len != cdt->cdt_max_requests) {
638                         /* cdt_max_requests has changed,
639                          * we need to allocate a new buffer
640                          */
641                         struct hsm_scan_request *tmp = NULL;
642                         int max_requests = cdt->cdt_max_requests;
643                         OBD_ALLOC_LARGE(tmp, max_requests *
644                                         sizeof(struct hsm_scan_request));
645                         if (!tmp) {
646                                 CERROR("Failed to resize request buffer, "
647                                        "keeping it at %d\n",
648                                        hsd.hsd_request_len);
649                         } else {
650                                 if (hsd.hsd_request != NULL)
651                                         OBD_FREE_LARGE(hsd.hsd_request,
652                                                        request_sz);
653
654                                 hsd.hsd_request_len = max_requests;
655                                 request_sz = hsd.hsd_request_len *
656                                         sizeof(struct hsm_scan_request);
657                                 hsd.hsd_request = tmp;
658                         }
659                 }
660
661                 hsd.hsd_action_count = 0;
662                 hsd.hsd_request_count = 0;
663                 hsd.hsd_one_restore = false;
664
665                 rc = cdt_llog_process(mti->mti_env, mdt, mdt_coordinator_cb,
666                                       &hsd, start_cat_idx, start_rec_idx,
667                                       WRITE);
668                 if (rc < 0)
669                         goto clean_cb_alloc;
670
671                 CDEBUG(D_HSM, "found %d requests to send\n",
672                        hsd.hsd_request_count);
673
674                 if (list_empty(&cdt->cdt_agents)) {
675                         CDEBUG(D_HSM, "no agent available, "
676                                       "coordinator sleeps\n");
677                         /* reset HSM scanning index range. */
678                         hsd.hsd_start_cat_idx = start_cat_idx;
679                         hsd.hsd_start_rec_idx = start_rec_idx;
680                         goto clean_cb_alloc;
681                 }
682
683                 /* Compute how many HAI we have in all the requests */
684                 updates_cnt = 0;
685                 for (i = 0; i < hsd.hsd_request_count; i++) {
686                         const struct hsm_scan_request *request =
687                                 &hsd.hsd_request[i];
688
689                         updates_cnt += request->hal->hal_count;
690                 }
691
692                 /* Allocate a temporary array to store the cookies to
693                  * update, and their status. */
694                 updates_sz = updates_cnt * sizeof(*updates);
695                 OBD_ALLOC_LARGE(updates, updates_sz);
696                 if (updates == NULL) {
697                         CERROR("%s: Cannot allocate memory (%d bytes) "
698                                "for %d updates. Too many HSM requests?\n",
699                                mdt_obd_name(mdt), updates_sz, updates_cnt);
700                         goto clean_cb_alloc;
701                 }
702
703                 /* here hsd contains a list of requests to be started */
704                 for (i = 0; i < hsd.hsd_request_count; i++) {
705                         struct hsm_scan_request *request = &hsd.hsd_request[i];
706                         struct hsm_action_list  *hal = request->hal;
707                         struct hsm_action_item  *hai;
708                         int                      j;
709
710                         /* still room for work ? */
711                         if (atomic_read(&cdt->cdt_request_count) >=
712                             cdt->cdt_max_requests)
713                                 break;
714
715                         rc = mdt_hsm_agent_send(mti, hal, 0);
716                         /* if failure, we suppose it is temporary
717                          * if the copy tool failed to do the request
718                          * it has to use hsm_progress
719                          */
720
721                         /* set up cookie vector to set records status
722                          * after copy tools start or failed
723                          */
724                         hai = hai_first(hal);
725                         for (j = 0; j < hal->hal_count; j++) {
726                                 updates[update_idx].cookie = hai->hai_cookie;
727                                 updates[update_idx].status =
728                                         (rc ? ARS_WAITING : ARS_STARTED);
729                                 hai = hai_next(hai);
730                                 update_idx++;
731                         }
732
733                         /* TODO: narrow down the HSM action range that already
734                          * scanned accroding to the cookies when a failure
735                          * occurs.
736                          */
737                         if (rc) {
738                                 hsd.hsd_start_cat_idx = start_cat_idx;
739                                 hsd.hsd_start_rec_idx = start_rec_idx;
740                         }
741                 }
742
743                 if (update_idx) {
744                         rc = mdt_agent_record_update(mti->mti_env, mdt,
745                                                      updates, update_idx);
746                         if (rc)
747                                 CERROR("%s: mdt_agent_record_update() failed, "
748                                        "rc=%d, cannot update records "
749                                        "for %d cookies\n",
750                                        mdt_obd_name(mdt), rc, update_idx);
751                 }
752
753                 OBD_FREE_LARGE(updates, updates_sz);
754
755 clean_cb_alloc:
756                 /* free hal allocated by callback */
757                 for (i = 0; i < hsd.hsd_request_count; i++) {
758                         struct hsm_scan_request *request = &hsd.hsd_request[i];
759
760                         OBD_FREE_LARGE(request->hal, request->hal_sz);
761                 }
762         }
763
764         if (hsd.hsd_request != NULL)
765                 OBD_FREE_LARGE(hsd.hsd_request, request_sz);
766
767         mdt_hsm_cdt_cleanup(mdt);
768
769         if (rc != 0)
770                 CERROR("%s: coordinator thread exiting, process=%d, rc=%d\n",
771                        mdt_obd_name(mdt), current->pid, rc);
772         else
773                 CDEBUG(D_HSM, "%s: coordinator thread exiting, process=%d,"
774                               " no error\n",
775                        mdt_obd_name(mdt), current->pid);
776
777         RETURN(rc);
778 }
779
780 int cdt_restore_handle_add(struct mdt_thread_info *mti, struct coordinator *cdt,
781                            const struct lu_fid *fid,
782                            const struct hsm_extent *he)
783 {
784         struct cdt_restore_handle *crh;
785         struct mdt_object *obj;
786         int rc;
787         ENTRY;
788
789         OBD_SLAB_ALLOC_PTR(crh, mdt_hsm_cdt_kmem);
790         if (crh == NULL)
791                 RETURN(-ENOMEM);
792
793         crh->crh_fid = *fid;
794         /* in V1 all file is restored
795          * crh->extent.start = he->offset;
796          * crh->extent.end = he->offset + he->length;
797          */
798         crh->crh_extent.start = 0;
799         crh->crh_extent.end = he->length;
800         /* get the layout lock */
801         mdt_lock_reg_init(&crh->crh_lh, LCK_EX);
802         obj = mdt_object_find_lock(mti, &crh->crh_fid, &crh->crh_lh,
803                                    MDS_INODELOCK_LAYOUT);
804         if (IS_ERR(obj))
805                 GOTO(out_crh, rc = PTR_ERR(obj));
806
807         /* We do not keep a reference on the object during the restore
808          * which can be very long. */
809         mdt_object_put(mti->mti_env, obj);
810
811         mutex_lock(&cdt->cdt_restore_lock);
812         if (unlikely(cdt->cdt_state == CDT_STOPPED ||
813                      cdt->cdt_state == CDT_STOPPING)) {
814                 mutex_unlock(&cdt->cdt_restore_lock);
815                 GOTO(out_lh, rc = -EAGAIN);
816         }
817
818         list_add_tail(&crh->crh_list, &cdt->cdt_restore_handle_list);
819         mutex_unlock(&cdt->cdt_restore_lock);
820
821         RETURN(0);
822 out_lh:
823         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
824 out_crh:
825         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
826
827         return rc;
828 }
829
830 /**
831  * lookup a restore handle by FID
832  * caller needs to hold cdt_restore_lock
833  * \param cdt [IN] coordinator
834  * \param fid [IN] FID
835  * \retval cdt_restore_handle found
836  * \retval NULL not found
837  */
838 struct cdt_restore_handle *cdt_restore_handle_find(struct coordinator *cdt,
839                                                    const struct lu_fid *fid)
840 {
841         struct cdt_restore_handle *crh;
842         ENTRY;
843
844         list_for_each_entry(crh, &cdt->cdt_restore_handle_list, crh_list) {
845                 if (lu_fid_eq(&crh->crh_fid, fid))
846                         RETURN(crh);
847         }
848
849         RETURN(NULL);
850 }
851
852 void cdt_restore_handle_del(struct mdt_thread_info *mti,
853                             struct coordinator *cdt, const struct lu_fid *fid)
854 {
855         struct cdt_restore_handle *crh;
856
857         /* give back layout lock */
858         mutex_lock(&cdt->cdt_restore_lock);
859         crh = cdt_restore_handle_find(cdt, fid);
860         if (crh != NULL)
861                 list_del(&crh->crh_list);
862         mutex_unlock(&cdt->cdt_restore_lock);
863
864         if (crh == NULL)
865                 return;
866
867         /* XXX We pass a NULL object since the restore handle does not
868          * keep a reference on the object being restored. */
869         mdt_object_unlock(mti, NULL, &crh->crh_lh, 1);
870         OBD_SLAB_FREE_PTR(crh, mdt_hsm_cdt_kmem);
871 }
872
873 /**
874  * data passed to llog_cat_process() callback
875  * to scan requests and take actions
876  */
877 struct hsm_restore_data {
878         struct mdt_thread_info  *hrd_mti;
879 };
880
881 /**
882  *  llog_cat_process() callback, used to:
883  *  - find restore request and allocate the restore handle
884  * \param env [IN] environment
885  * \param llh [IN] llog handle
886  * \param hdr [IN] llog record
887  * \param data [IN/OUT] cb data = struct hsm_restore_data
888  * \retval 0 success
889  * \retval -ve failure
890  */
891 static int hsm_restore_cb(const struct lu_env *env,
892                           struct llog_handle *llh,
893                           struct llog_rec_hdr *hdr, void *data)
894 {
895         struct llog_agent_req_rec       *larr;
896         struct hsm_restore_data         *hrd;
897         struct hsm_action_item          *hai;
898         struct mdt_thread_info          *mti;
899         struct coordinator              *cdt;
900         int rc;
901         ENTRY;
902
903         hrd = data;
904         mti = hrd->hrd_mti;
905         cdt = &mti->mti_mdt->mdt_coordinator;
906
907         larr = (struct llog_agent_req_rec *)hdr;
908         hai = &larr->arr_hai;
909         if (hai->hai_cookie >= cdt->cdt_last_cookie) {
910                 /* update the cookie to avoid collision */
911                 cdt->cdt_last_cookie = hai->hai_cookie + 1;
912         }
913
914         if (hai->hai_action != HSMA_RESTORE ||
915             agent_req_in_final_state(larr->arr_status))
916                 RETURN(0);
917
918         /* restore request not in a final state */
919
920         /* force replay of restore requests left in started state from previous
921          * CDT context, to be canceled later if finally found to be incompatible
922          * when being re-started */
923         if (larr->arr_status == ARS_STARTED) {
924                 larr->arr_status = ARS_WAITING;
925                 larr->arr_req_change = ktime_get_real_seconds();
926                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
927                 if (rc != 0)
928                         GOTO(out, rc);
929         }
930
931         rc = cdt_restore_handle_add(mti, cdt, &hai->hai_fid, &hai->hai_extent);
932 out:
933         RETURN(rc);
934 }
935
936 /**
937  * restore coordinator state at startup
938  * the goal is to take a layout lock for each registered restore request
939  * \param mti [IN] context
940  */
941 static int mdt_hsm_pending_restore(struct mdt_thread_info *mti)
942 {
943         struct hsm_restore_data  hrd;
944         int                      rc;
945         ENTRY;
946
947         hrd.hrd_mti = mti;
948
949         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, hsm_restore_cb, &hrd,
950                               0, 0, WRITE);
951
952         RETURN(rc);
953 }
954
955 int hsm_init_ucred(struct lu_ucred *uc)
956 {
957         ENTRY;
958         uc->uc_valid = UCRED_OLD;
959         uc->uc_o_uid = 0;
960         uc->uc_o_gid = 0;
961         uc->uc_o_fsuid = 0;
962         uc->uc_o_fsgid = 0;
963         uc->uc_uid = 0;
964         uc->uc_gid = 0;
965         uc->uc_fsuid = 0;
966         uc->uc_fsgid = 0;
967         uc->uc_suppgids[0] = -1;
968         uc->uc_suppgids[1] = -1;
969         uc->uc_cap = cap_combine(CAP_FS_SET, CAP_NFSD_SET);
970         uc->uc_umask = 0777;
971         uc->uc_ginfo = NULL;
972         uc->uc_identity = NULL;
973         /* always record internal HSM activity if also enabled globally */
974         uc->uc_enable_audit = 1;
975
976         RETURN(0);
977 }
978
979 /**
980  * initialize coordinator struct
981  * \param mdt [IN] device
982  * \retval 0 success
983  * \retval -ve failure
984  */
985 int mdt_hsm_cdt_init(struct mdt_device *mdt)
986 {
987         struct coordinator      *cdt = &mdt->mdt_coordinator;
988         struct mdt_thread_info  *cdt_mti = NULL;
989         int                      rc;
990         ENTRY;
991
992         init_waitqueue_head(&cdt->cdt_waitq);
993         init_rwsem(&cdt->cdt_llog_lock);
994         init_rwsem(&cdt->cdt_agent_lock);
995         init_rwsem(&cdt->cdt_request_lock);
996         mutex_init(&cdt->cdt_restore_lock);
997         mutex_init(&cdt->cdt_state_lock);
998         set_cdt_state(cdt, CDT_STOPPED);
999
1000         INIT_LIST_HEAD(&cdt->cdt_request_list);
1001         INIT_LIST_HEAD(&cdt->cdt_agents);
1002         INIT_LIST_HEAD(&cdt->cdt_restore_handle_list);
1003
1004         cdt->cdt_request_cookie_hash = cfs_hash_create("REQUEST_COOKIE_HASH",
1005                                                        CFS_HASH_BITS_MIN,
1006                                                        CFS_HASH_BITS_MAX,
1007                                                        CFS_HASH_BKT_BITS,
1008                                                        0 /* extra bytes */,
1009                                                        CFS_HASH_MIN_THETA,
1010                                                        CFS_HASH_MAX_THETA,
1011                                                 &cdt_request_cookie_hash_ops,
1012                                                        CFS_HASH_DEFAULT);
1013         if (cdt->cdt_request_cookie_hash == NULL)
1014                 RETURN(-ENOMEM);
1015
1016         cdt->cdt_agent_record_hash = cfs_hash_create("AGENT_RECORD_HASH",
1017                                                      CFS_HASH_BITS_MIN,
1018                                                      CFS_HASH_BITS_MAX,
1019                                                      CFS_HASH_BKT_BITS,
1020                                                      0 /* extra bytes */,
1021                                                      CFS_HASH_MIN_THETA,
1022                                                      CFS_HASH_MAX_THETA,
1023                                                      &cdt_agent_record_hash_ops,
1024                                                      CFS_HASH_DEFAULT);
1025         if (cdt->cdt_agent_record_hash == NULL)
1026                 GOTO(out_request_cookie_hash, rc = -ENOMEM);
1027
1028         rc = lu_env_init(&cdt->cdt_env, LCT_MD_THREAD);
1029         if (rc < 0)
1030                 GOTO(out_agent_record_hash, rc);
1031
1032         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1033         rc = lu_context_init(&cdt->cdt_session, LCT_SERVER_SESSION);
1034         if (rc < 0)
1035                 GOTO(out_env, rc);
1036
1037         lu_context_enter(&cdt->cdt_session);
1038         cdt->cdt_env.le_ses = &cdt->cdt_session;
1039
1040         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1041         LASSERT(cdt_mti != NULL);
1042
1043         cdt_mti->mti_env = &cdt->cdt_env;
1044         cdt_mti->mti_mdt = mdt;
1045
1046         hsm_init_ucred(mdt_ucred(cdt_mti));
1047
1048         /* default values for sysfs tunnables
1049          * can be override by MGS conf */
1050         cdt->cdt_default_archive_id = 1;
1051         cdt->cdt_grace_delay = 60;
1052         cdt->cdt_loop_period = 10;
1053         cdt->cdt_max_requests = 3;
1054         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1055         cdt->cdt_active_req_timeout = 3600;
1056
1057         /* by default do not remove archives on last unlink */
1058         cdt->cdt_remove_archive_on_last_unlink = false;
1059
1060         RETURN(0);
1061
1062 out_env:
1063         lu_env_fini(&cdt->cdt_env);
1064 out_agent_record_hash:
1065         cfs_hash_putref(cdt->cdt_agent_record_hash);
1066         cdt->cdt_agent_record_hash = NULL;
1067 out_request_cookie_hash:
1068         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1069         cdt->cdt_request_cookie_hash = NULL;
1070
1071         return rc;
1072 }
1073
1074 /**
1075  * free a coordinator thread
1076  * \param mdt [IN] device
1077  */
1078 int  mdt_hsm_cdt_fini(struct mdt_device *mdt)
1079 {
1080         struct coordinator *cdt = &mdt->mdt_coordinator;
1081         ENTRY;
1082
1083         lu_context_exit(cdt->cdt_env.le_ses);
1084         lu_context_fini(cdt->cdt_env.le_ses);
1085
1086         lu_env_fini(&cdt->cdt_env);
1087
1088         cfs_hash_putref(cdt->cdt_agent_record_hash);
1089         cdt->cdt_agent_record_hash = NULL;
1090
1091         cfs_hash_putref(cdt->cdt_request_cookie_hash);
1092         cdt->cdt_request_cookie_hash = NULL;
1093
1094         RETURN(0);
1095 }
1096
1097 /**
1098  * start a coordinator thread
1099  * \param mdt [IN] device
1100  * \retval 0 success
1101  * \retval -ve failure
1102  */
1103 static int mdt_hsm_cdt_start(struct mdt_device *mdt)
1104 {
1105         struct coordinator *cdt = &mdt->mdt_coordinator;
1106         struct mdt_thread_info *cdt_mti;
1107         unsigned int i = 0;
1108         int rc;
1109         void *ptr;
1110         struct task_struct *task;
1111         ENTRY;
1112
1113         /* functions defined but not yet used
1114          * this avoid compilation warning
1115          */
1116         ptr = dump_requests;
1117
1118         rc = set_cdt_state(cdt, CDT_INIT);
1119         if (rc) {
1120                 CERROR("%s: Coordinator already started or stopping\n",
1121                        mdt_obd_name(mdt));
1122                 RETURN(-EALREADY);
1123         }
1124
1125         BUILD_BUG_ON(BIT(CDT_POLICY_SHIFT_COUNT - 1) != CDT_POLICY_LAST);
1126         cdt->cdt_policy = CDT_DEFAULT_POLICY;
1127
1128         /* just need to be larger than previous one */
1129         /* cdt_last_cookie is protected by cdt_llog_lock */
1130         cdt->cdt_last_cookie = ktime_get_real_seconds();
1131         atomic_set(&cdt->cdt_request_count, 0);
1132         atomic_set(&cdt->cdt_archive_count, 0);
1133         atomic_set(&cdt->cdt_restore_count, 0);
1134         atomic_set(&cdt->cdt_remove_count, 0);
1135         cdt->cdt_user_request_mask = (1UL << HSMA_RESTORE);
1136         cdt->cdt_group_request_mask = (1UL << HSMA_RESTORE);
1137         cdt->cdt_other_request_mask = (1UL << HSMA_RESTORE);
1138
1139         /* wait until MDD initialize hsm actions llog */
1140         while (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state) && i < obd_timeout) {
1141                 schedule_timeout_interruptible(cfs_time_seconds(1));
1142                 i++;
1143         }
1144         if (!test_bit(MDT_FL_CFGLOG, &mdt->mdt_state))
1145                 CWARN("%s: trying to init HSM before MDD\n", mdt_obd_name(mdt));
1146
1147         /* to avoid deadlock when start is made through sysfs
1148          * sysfs entries are created by the coordinator thread
1149          */
1150         /* set up list of started restore requests */
1151         cdt_mti = lu_context_key_get(&cdt->cdt_env.le_ctx, &mdt_thread_key);
1152         rc = mdt_hsm_pending_restore(cdt_mti);
1153         if (rc)
1154                 CERROR("%s: cannot take the layout locks needed"
1155                        " for registered restore: %d\n",
1156                        mdt_obd_name(mdt), rc);
1157
1158         if (mdt->mdt_bottom->dd_rdonly)
1159                 RETURN(0);
1160
1161         task = kthread_run(mdt_coordinator, cdt_mti, "hsm_cdtr");
1162         if (IS_ERR(task)) {
1163                 rc = PTR_ERR(task);
1164                 set_cdt_state(cdt, CDT_STOPPED);
1165                 CERROR("%s: error starting coordinator thread: %d\n",
1166                        mdt_obd_name(mdt), rc);
1167         } else {
1168                 cdt->cdt_task = task;
1169                 wait_event(cdt->cdt_waitq,
1170                            cdt->cdt_state != CDT_INIT);
1171                 CDEBUG(D_HSM, "%s: coordinator thread started\n",
1172                        mdt_obd_name(mdt));
1173                 rc = 0;
1174         }
1175
1176         RETURN(rc);
1177 }
1178
1179 /**
1180  * stop a coordinator thread
1181  * \param mdt [IN] device
1182  */
1183 int mdt_hsm_cdt_stop(struct mdt_device *mdt)
1184 {
1185         struct coordinator *cdt = &mdt->mdt_coordinator;
1186         int rc;
1187
1188         ENTRY;
1189         /* stop coordinator thread */
1190         rc = set_cdt_state(cdt, CDT_STOPPING);
1191         if (rc == 0) {
1192                 kthread_stop(cdt->cdt_task);
1193                 cdt->cdt_task = NULL;
1194                 set_cdt_state(cdt, CDT_STOPPED);
1195         }
1196
1197         RETURN(rc);
1198 }
1199
1200 static int mdt_hsm_set_exists(struct mdt_thread_info *mti,
1201                               const struct lu_fid *fid,
1202                               u32 archive_id)
1203 {
1204         struct mdt_object *obj;
1205         struct md_hsm mh;
1206         int rc;
1207
1208         obj = mdt_hsm_get_md_hsm(mti, fid, &mh);
1209         if (IS_ERR(obj))
1210                 GOTO(out, rc = PTR_ERR(obj));
1211
1212         if (mh.mh_flags & HS_EXISTS &&
1213             mh.mh_arch_id == archive_id)
1214                 GOTO(out_obj, rc = 0);
1215
1216         mh.mh_flags |= HS_EXISTS;
1217         mh.mh_arch_id = archive_id;
1218         rc = mdt_hsm_attr_set(mti, obj, &mh);
1219
1220 out_obj:
1221         mdt_object_put(mti->mti_env, obj);
1222 out:
1223         return rc;
1224 }
1225
1226 /**
1227  * register all requests from an hal in the memory list
1228  * \param mti [IN] context
1229  * \param hal [IN] request
1230  * \param uuid [OUT] in case of CANCEL, the uuid of the agent
1231  *  which is running the CT
1232  * \retval 0 success
1233  * \retval -ve failure
1234  */
1235 int mdt_hsm_add_hal(struct mdt_thread_info *mti,
1236                     struct hsm_action_list *hal, struct obd_uuid *uuid)
1237 {
1238         struct mdt_device       *mdt = mti->mti_mdt;
1239         struct coordinator      *cdt = &mdt->mdt_coordinator;
1240         struct hsm_action_item  *hai;
1241         int                      rc = 0, i;
1242         ENTRY;
1243
1244         /* register request in memory list */
1245         hai = hai_first(hal);
1246         for (i = 0; i < hal->hal_count; i++, hai = hai_next(hai)) {
1247                 struct cdt_agent_req *car;
1248
1249                 /* in case of a cancel request, we first mark the ondisk
1250                  * record of the request we want to stop as canceled
1251                  * this does not change the cancel record
1252                  * it will be done when updating the request status
1253                  */
1254                 if (hai->hai_action == HSMA_CANCEL) {
1255                         struct hsm_record_update update = {
1256                                 .cookie = hai->hai_cookie,
1257                                 .status = ARS_CANCELED,
1258                         };
1259
1260                         rc = mdt_agent_record_update(mti->mti_env, mti->mti_mdt,
1261                                                      &update, 1);
1262                         if (rc) {
1263                                 CERROR("%s: mdt_agent_record_update() failed, "
1264                                        "rc=%d, cannot update status to %s "
1265                                        "for cookie %#llx\n",
1266                                        mdt_obd_name(mdt), rc,
1267                                        agent_req_status2name(ARS_CANCELED),
1268                                        hai->hai_cookie);
1269                                 GOTO(out, rc);
1270                         }
1271
1272                         /* find the running request to set it canceled */
1273                         car = mdt_cdt_find_request(cdt, hai->hai_cookie);
1274                         if (car != NULL) {
1275                                 car->car_canceled = 1;
1276                                 /* uuid has to be changed to the one running the
1277                                 * request to cancel */
1278                                 *uuid = car->car_uuid;
1279                                 mdt_cdt_put_request(car);
1280                         }
1281                         /* no need to memorize cancel request
1282                          * this also avoid a deadlock when we receive
1283                          * a purge all requests command
1284                          */
1285                         continue;
1286                 }
1287
1288                 if (hai->hai_action == HSMA_ARCHIVE) {
1289                         rc = mdt_hsm_set_exists(mti, &hai->hai_fid,
1290                                                 hal->hal_archive_id);
1291                         if (rc == -ENOENT)
1292                                 continue;
1293                         else if (rc < 0)
1294                                 GOTO(out, rc);
1295                 }
1296
1297                 car = mdt_cdt_alloc_request(hal->hal_archive_id, hal->hal_flags,
1298                                             uuid, hai);
1299                 if (IS_ERR(car))
1300                         GOTO(out, rc = PTR_ERR(car));
1301
1302                 rc = mdt_cdt_add_request(cdt, car);
1303                 if (rc != 0)
1304                         mdt_cdt_free_request(car);
1305         }
1306 out:
1307         RETURN(rc);
1308 }
1309
1310 /**
1311  * swap layouts between 2 fids
1312  * \param mti [IN] context
1313  * \param obj [IN]
1314  * \param dfid [IN]
1315  * \param mh_common [IN] MD HSM
1316  */
1317 static int hsm_swap_layouts(struct mdt_thread_info *mti,
1318                             struct mdt_object *obj, const struct lu_fid *dfid,
1319                             struct md_hsm *mh_common)
1320 {
1321         struct mdt_object       *dobj;
1322         struct mdt_lock_handle  *dlh;
1323         int                      rc;
1324         ENTRY;
1325
1326         if (!mdt_object_exists(obj))
1327                 GOTO(out, rc = -ENOENT);
1328
1329         /* we already have layout lock on obj so take only
1330          * on dfid */
1331         dlh = &mti->mti_lh[MDT_LH_OLD];
1332         mdt_lock_reg_init(dlh, LCK_EX);
1333         dobj = mdt_object_find_lock(mti, dfid, dlh, MDS_INODELOCK_LAYOUT);
1334         if (IS_ERR(dobj))
1335                 GOTO(out, rc = PTR_ERR(dobj));
1336
1337         /* if copy tool closes the volatile before sending the final
1338          * progress through llapi_hsm_copy_end(), all the objects
1339          * are removed and mdd_swap_layout LBUG */
1340         if (!mdt_object_exists(dobj)) {
1341                 CERROR("%s: Copytool has closed volatile file "DFID"\n",
1342                        mdt_obd_name(mti->mti_mdt), PFID(dfid));
1343                 GOTO(out_dobj, rc = -ENOENT);
1344         }
1345         /* Since we only handle restores here, unconditionally use
1346          * SWAP_LAYOUTS_MDS_HSM flag to ensure original layout will
1347          * be preserved in case of failure during swap_layout and not
1348          * leave a file in an intermediate but incoherent state.
1349          * But need to setup HSM xattr of data FID before, reuse
1350          * mti and mh presets for FID in hsm_cdt_request_completed(),
1351          * only need to clear RELEASED and DIRTY.
1352          */
1353         mh_common->mh_flags &= ~(HS_RELEASED | HS_DIRTY);
1354         rc = mdt_hsm_attr_set(mti, dobj, mh_common);
1355         if (rc == 0)
1356                 rc = mo_swap_layouts(mti->mti_env,
1357                                      mdt_object_child(obj),
1358                                      mdt_object_child(dobj),
1359                                      SWAP_LAYOUTS_MDS_HSM);
1360         if (rc == 0) {
1361                 rc = mdt_lsom_downgrade(mti, obj);
1362                 if (rc)
1363                         CDEBUG(D_INODE,
1364                                "%s: File fid="DFID" SOM "
1365                                "downgrade failed, rc = %d\n",
1366                                mdt_obd_name(mti->mti_mdt),
1367                                PFID(mdt_object_fid(obj)), rc);
1368         }
1369 out_dobj:
1370         mdt_object_unlock_put(mti, dobj, dlh, 1);
1371 out:
1372         RETURN(rc);
1373 }
1374
1375 /**
1376  * update status of a completed request
1377  * \param mti [IN] context
1378  * \param pgs [IN] progress of the copy tool
1379  * \retval 0 success
1380  * \retval -ve failure
1381  */
1382 static int hsm_cdt_request_completed(struct mdt_thread_info *mti,
1383                                      struct hsm_progress_kernel *pgs,
1384                                      const struct cdt_agent_req *car,
1385                                      enum agent_req_status *status)
1386 {
1387         const struct lu_env *env = mti->mti_env;
1388         struct mdt_device *mdt = mti->mti_mdt;
1389         struct coordinator *cdt = &mdt->mdt_coordinator;
1390         struct mdt_object *obj = NULL;
1391         enum changelog_rec_flags clf_flags = 0;
1392         struct md_hsm mh;
1393         bool is_mh_changed;
1394         bool need_changelog = true;
1395         int rc = 0;
1396
1397         ENTRY;
1398         /* default is to retry */
1399         *status = ARS_WAITING;
1400
1401         /* find object by FID, mdt_hsm_get_md_hsm() returns obj or err
1402          * if error/removed continue anyway to get correct reporting done */
1403         obj = mdt_hsm_get_md_hsm(mti, &car->car_hai->hai_fid, &mh);
1404         /* we will update MD HSM only if needed */
1405         is_mh_changed = false;
1406
1407         /* no need to change mh->mh_arch_id
1408          * mdt_hsm_get_md_hsm() got it from disk and it is still valid
1409          */
1410         if (pgs->hpk_errval != 0) {
1411                 switch (pgs->hpk_errval) {
1412                 case ENOSYS:
1413                         /* the copy tool does not support cancel
1414                          * so the cancel request is failed
1415                          * As we cannot distinguish a cancel progress
1416                          * from another action progress (they have the
1417                          * same cookie), we suppose here the CT returns
1418                          * ENOSYS only if does not support cancel
1419                          */
1420                         /* this can also happen when cdt calls it to
1421                          * for a timed out request */
1422                         *status = ARS_FAILED;
1423                         /* to have a cancel event in changelog */
1424                         pgs->hpk_errval = ECANCELED;
1425                         break;
1426                 case ECANCELED:
1427                         /* the request record has already been set to
1428                          * ARS_CANCELED, this set the cancel request
1429                          * to ARS_SUCCEED */
1430                         *status = ARS_SUCCEED;
1431                         break;
1432                 default:
1433                         /* retry only if current policy or requested, and
1434                          * object is not on error/removed */
1435                         *status = (cdt->cdt_policy & CDT_NORETRY_ACTION ||
1436                                    !(pgs->hpk_flags & HP_FLAG_RETRY) ||
1437                                    IS_ERR(obj)) ? ARS_FAILED : ARS_WAITING;
1438                         break;
1439                 }
1440
1441                 if (pgs->hpk_errval > CLF_HSM_MAXERROR) {
1442                         CERROR("%s: Request %#llx on "DFID
1443                                " failed, error code %d too large\n",
1444                                mdt_obd_name(mdt),
1445                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1446                                pgs->hpk_errval);
1447                         hsm_set_cl_error(&clf_flags, CLF_HSM_ERROVERFLOW);
1448                         rc = -EINVAL;
1449                 } else {
1450                         hsm_set_cl_error(&clf_flags, pgs->hpk_errval);
1451                 }
1452
1453                 switch (car->car_hai->hai_action) {
1454                 case HSMA_ARCHIVE:
1455                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1456                         break;
1457                 case HSMA_RESTORE:
1458                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1459                         break;
1460                 case HSMA_REMOVE:
1461                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1462                         break;
1463                 case HSMA_CANCEL:
1464                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1465                         CERROR("%s: Failed request %#llx on "DFID
1466                                " cannot be a CANCEL\n",
1467                                mdt_obd_name(mdt),
1468                                pgs->hpk_cookie,
1469                                PFID(&pgs->hpk_fid));
1470                         break;
1471                 default:
1472                         CERROR("%s: Failed request %#llx on "DFID
1473                                " %d is an unknown action\n",
1474                                mdt_obd_name(mdt),
1475                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1476                                car->car_hai->hai_action);
1477                         rc = -EINVAL;
1478                         break;
1479                 }
1480         } else {
1481                 *status = ARS_SUCCEED;
1482                 switch (car->car_hai->hai_action) {
1483                 case HSMA_ARCHIVE:
1484                         hsm_set_cl_event(&clf_flags, HE_ARCHIVE);
1485                         /* set ARCHIVE keep EXIST and clear LOST and
1486                          * DIRTY */
1487                         mh.mh_arch_ver = pgs->hpk_data_version;
1488                         mh.mh_flags |= HS_ARCHIVED;
1489                         mh.mh_flags &= ~(HS_LOST|HS_DIRTY);
1490                         is_mh_changed = true;
1491                         break;
1492                 case HSMA_RESTORE:
1493                         hsm_set_cl_event(&clf_flags, HE_RESTORE);
1494
1495                         /* do not clear RELEASED and DIRTY here
1496                          * this will occur in hsm_swap_layouts()
1497                          */
1498
1499                         /* Restoring has changed the file version on
1500                          * disk. */
1501                         mh.mh_arch_ver = pgs->hpk_data_version;
1502                         is_mh_changed = true;
1503                         break;
1504                 case HSMA_REMOVE:
1505                         hsm_set_cl_event(&clf_flags, HE_REMOVE);
1506                         /* clear ARCHIVED EXISTS and LOST */
1507                         mh.mh_flags &= ~(HS_ARCHIVED | HS_EXISTS | HS_LOST);
1508                         is_mh_changed = true;
1509                         break;
1510                 case HSMA_CANCEL:
1511                         hsm_set_cl_event(&clf_flags, HE_CANCEL);
1512                         CERROR("%s: Successful request %#llx on "DFID" cannot be a CANCEL\n",
1513                                mdt_obd_name(mdt),
1514                                pgs->hpk_cookie,
1515                                PFID(&pgs->hpk_fid));
1516                         break;
1517                 default:
1518                         CERROR("%s: Successful request %#llx on "DFID" %d is an unknown action\n",
1519                                mdt_obd_name(mdt),
1520                                pgs->hpk_cookie, PFID(&pgs->hpk_fid),
1521                                car->car_hai->hai_action);
1522                         rc = -EINVAL;
1523                         break;
1524                 }
1525         }
1526
1527         /* rc != 0 means error when analysing action, it may come from
1528          * a crasy CT no need to manage DIRTY
1529          * and if mdt_hsm_get_md_hsm() has returned an error, mh has not been
1530          * filled
1531          */
1532         if (rc == 0 && !IS_ERR(obj))
1533                 hsm_set_cl_flags(&clf_flags,
1534                                  mh.mh_flags & HS_DIRTY ? CLF_HSM_DIRTY : 0);
1535
1536         /* unlock is done later, after layout lock management */
1537         if (is_mh_changed && !IS_ERR(obj))
1538                 rc = mdt_hsm_attr_set(mti, obj, &mh);
1539
1540         /* we give back layout lock only if restore was successful or
1541          * if no retry will be attempted and if object is still alive,
1542          * in other cases we just unlock the object */
1543         if (car->car_hai->hai_action == HSMA_RESTORE) {
1544                 struct mdt_lock_handle *lh;
1545
1546                 /* restore in data FID done, we swap the layouts
1547                  * only if restore is successful */
1548                 if (pgs->hpk_errval == 0 && !IS_ERR(obj)) {
1549                         rc = hsm_swap_layouts(mti, obj, &car->car_hai->hai_dfid,
1550                                               &mh);
1551                         if (rc) {
1552                                 if (cdt->cdt_policy & CDT_NORETRY_ACTION)
1553                                         *status = ARS_FAILED;
1554                                 pgs->hpk_errval = -rc;
1555                         }
1556                 }
1557                 /* we have to retry, so keep layout lock */
1558                 if (*status == ARS_WAITING)
1559                         GOTO(out, rc);
1560
1561                 /* restore special case, need to create ChangeLog record
1562                  * before to give back layout lock to avoid concurrent
1563                  * file updater to post out of order ChangeLog */
1564                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1565                              &car->car_hai->hai_fid);
1566                 need_changelog = false;
1567
1568                 cdt_restore_handle_del(mti, cdt, &car->car_hai->hai_fid);
1569                 if (!IS_ERR_OR_NULL(obj)) {
1570                         /* flush UPDATE lock so attributes are upadated */
1571                         lh = &mti->mti_lh[MDT_LH_OLD];
1572                         mdt_lock_reg_init(lh, LCK_EX);
1573                         mdt_object_lock(mti, obj, lh, MDS_INODELOCK_UPDATE);
1574                         mdt_object_unlock(mti, obj, lh, 1);
1575                 }
1576         }
1577
1578         GOTO(out, rc);
1579
1580 out:
1581         /* always add a ChangeLog record */
1582         if (need_changelog)
1583                 mo_changelog(env, CL_HSM, clf_flags, mdt->mdt_child,
1584                              &car->car_hai->hai_fid);
1585
1586         if (!IS_ERR(obj))
1587                 mdt_object_put(mti->mti_env, obj);
1588
1589         RETURN(rc);
1590 }
1591
1592 /**
1593  * update status of a request
1594  * \param mti [IN] context
1595  * \param pgs [IN] progress of the copy tool
1596  * \retval 0 success
1597  * \retval -ve failure
1598  */
1599 int mdt_hsm_update_request_state(struct mdt_thread_info *mti,
1600                                  struct hsm_progress_kernel *pgs)
1601 {
1602         struct mdt_device       *mdt = mti->mti_mdt;
1603         struct coordinator      *cdt = &mdt->mdt_coordinator;
1604         struct cdt_agent_req    *car;
1605         int                      rc = 0;
1606         ENTRY;
1607
1608         /* no coordinator started, so we cannot serve requests */
1609         if (cdt->cdt_state == CDT_STOPPED)
1610                 RETURN(-EAGAIN);
1611
1612         /* first do sanity checks */
1613         car = mdt_cdt_update_request(cdt, pgs);
1614         if (IS_ERR(car)) {
1615                 CERROR("%s: Cannot find running request for cookie %#llx"
1616                        " on fid="DFID"\n",
1617                        mdt_obd_name(mdt),
1618                        pgs->hpk_cookie, PFID(&pgs->hpk_fid));
1619
1620                 RETURN(PTR_ERR(car));
1621         }
1622
1623         CDEBUG(D_HSM, "Progress received for fid="DFID" cookie=%#llx"
1624                       " action=%s flags=%d err=%d fid="DFID" dfid="DFID"\n",
1625                       PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1626                       hsm_copytool_action2name(car->car_hai->hai_action),
1627                       pgs->hpk_flags, pgs->hpk_errval,
1628                       PFID(&car->car_hai->hai_fid),
1629                       PFID(&car->car_hai->hai_dfid));
1630
1631         /* progress is done on FID or data FID depending of the action and
1632          * of the copy progress */
1633         /* for restore progress is used to send back the data FID to cdt */
1634         if (car->car_hai->hai_action == HSMA_RESTORE &&
1635             lu_fid_eq(&car->car_hai->hai_fid, &car->car_hai->hai_dfid))
1636                 car->car_hai->hai_dfid = pgs->hpk_fid;
1637
1638         if ((car->car_hai->hai_action == HSMA_RESTORE ||
1639              car->car_hai->hai_action == HSMA_ARCHIVE) &&
1640             (!lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_dfid) &&
1641              !lu_fid_eq(&pgs->hpk_fid, &car->car_hai->hai_fid))) {
1642                 CERROR("%s: Progress on "DFID" for cookie %#llx"
1643                        " does not match request FID "DFID" nor data FID "
1644                        DFID"\n",
1645                        mdt_obd_name(mdt),
1646                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1647                        PFID(&car->car_hai->hai_fid),
1648                        PFID(&car->car_hai->hai_dfid));
1649                 GOTO(out, rc = -EINVAL);
1650         }
1651
1652         if (pgs->hpk_errval != 0 && !(pgs->hpk_flags & HP_FLAG_COMPLETED)) {
1653                 CERROR("%s: Progress on "DFID" for cookie %#llx action=%s"
1654                        " is not coherent (err=%d and not completed"
1655                        " (flags=%d))\n",
1656                        mdt_obd_name(mdt),
1657                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1658                        hsm_copytool_action2name(car->car_hai->hai_action),
1659                        pgs->hpk_errval, pgs->hpk_flags);
1660                 GOTO(out, rc = -EINVAL);
1661         }
1662
1663         /* now progress is valid */
1664
1665         /* we use a root like ucred */
1666         hsm_init_ucred(mdt_ucred(mti));
1667
1668         if (pgs->hpk_flags & HP_FLAG_COMPLETED) {
1669                 enum agent_req_status status;
1670                 struct hsm_record_update update;
1671                 int rc1;
1672
1673                 rc = hsm_cdt_request_completed(mti, pgs, car, &status);
1674
1675                 CDEBUG(D_HSM, "updating record: fid="DFID" cookie=%#llx action=%s "
1676                               "status=%s\n",
1677                        PFID(&pgs->hpk_fid), pgs->hpk_cookie,
1678                        hsm_copytool_action2name(car->car_hai->hai_action),
1679                        agent_req_status2name(status));
1680
1681                 /* update record first (LU-9075) */
1682                 update.cookie = pgs->hpk_cookie;
1683                 update.status = status;
1684
1685                 rc1 = mdt_agent_record_update(mti->mti_env, mdt,
1686                                               &update, 1);
1687                 if (rc1)
1688                         CERROR("%s: mdt_agent_record_update() failed,"
1689                                " rc=%d, cannot update status to %s"
1690                                " for cookie %#llx\n",
1691                                mdt_obd_name(mdt), rc1,
1692                                agent_req_status2name(status),
1693                                pgs->hpk_cookie);
1694                 rc = (rc != 0 ? rc : rc1);
1695
1696                 /* then remove request from memory list (LU-9075) */
1697                 mdt_cdt_remove_request(cdt, pgs->hpk_cookie);
1698
1699                 /* ct has completed a request, so a slot is available,
1700                  * signal the coordinator to find new work */
1701                 mdt_hsm_cdt_event(cdt);
1702         } else {
1703                 /* if copytool send a progress on a canceled request
1704                  * we inform copytool it should stop
1705                  */
1706                 if (car->car_canceled == 1)
1707                         rc = -ECANCELED;
1708         }
1709         GOTO(out, rc);
1710
1711 out:
1712         /* remove ref got from mdt_cdt_update_request() */
1713         mdt_cdt_put_request(car);
1714
1715         return rc;
1716 }
1717
1718
1719 /**
1720  * data passed to llog_cat_process() callback
1721  * to cancel requests
1722  */
1723 struct hsm_cancel_all_data {
1724         struct mdt_device       *mdt;
1725 };
1726
1727 /**
1728  *  llog_cat_process() callback, used to:
1729  *  - purge all requests
1730  * \param env [IN] environment
1731  * \param llh [IN] llog handle
1732  * \param hdr [IN] llog record
1733  * \param data [IN] cb data = struct hsm_cancel_all_data
1734  * \retval 0 success
1735  * \retval -ve failure
1736  */
1737 static int mdt_cancel_all_cb(const struct lu_env *env,
1738                              struct llog_handle *llh,
1739                              struct llog_rec_hdr *hdr, void *data)
1740 {
1741         struct llog_agent_req_rec       *larr;
1742         struct hsm_cancel_all_data      *hcad;
1743         int                              rc = 0;
1744         ENTRY;
1745
1746         larr = (struct llog_agent_req_rec *)hdr;
1747         hcad = data;
1748         if (larr->arr_status == ARS_WAITING ||
1749             larr->arr_status == ARS_STARTED) {
1750                 larr->arr_status = ARS_CANCELED;
1751                 larr->arr_req_change = ktime_get_real_seconds();
1752                 rc = llog_write(env, llh, hdr, hdr->lrh_index);
1753         }
1754
1755         RETURN(rc);
1756 }
1757
1758 /**
1759  * cancel all actions
1760  * \param obd [IN] MDT device
1761  */
1762 static int hsm_cancel_all_actions(struct mdt_device *mdt)
1763 {
1764         struct lu_env                    env;
1765         struct lu_context                session;
1766         struct mdt_thread_info          *mti;
1767         struct coordinator              *cdt = &mdt->mdt_coordinator;
1768         struct cdt_agent_req            *car;
1769         struct hsm_action_list          *hal = NULL;
1770         struct hsm_action_item          *hai;
1771         struct hsm_cancel_all_data       hcad;
1772         int                              hal_sz = 0, hal_len, rc;
1773         enum cdt_states                  old_state;
1774         ENTRY;
1775
1776         rc = lu_env_init(&env, LCT_MD_THREAD);
1777         if (rc < 0)
1778                 RETURN(rc);
1779
1780         /* for mdt_ucred(), lu_ucred stored in lu_ucred_key */
1781         rc = lu_context_init(&session, LCT_SERVER_SESSION);
1782         if (rc < 0)
1783                 GOTO(out_env, rc);
1784
1785         lu_context_enter(&session);
1786         env.le_ses = &session;
1787
1788         mti = lu_context_key_get(&env.le_ctx, &mdt_thread_key);
1789         LASSERT(mti != NULL);
1790
1791         mti->mti_env = &env;
1792         mti->mti_mdt = mdt;
1793
1794         hsm_init_ucred(mdt_ucred(mti));
1795
1796         mutex_lock(&cdt->cdt_state_lock);
1797         old_state = cdt->cdt_state;
1798
1799         /* disable coordinator */
1800         rc = set_cdt_state_locked(cdt, CDT_DISABLE);
1801         if (rc)
1802                 GOTO(out_cdt_state_unlock, rc);
1803
1804         /* send cancel to all running requests */
1805         down_read(&cdt->cdt_request_lock);
1806         list_for_each_entry(car, &cdt->cdt_request_list, car_request_list) {
1807                 mdt_cdt_get_request(car);
1808                 /* request is not yet removed from list, it will be done
1809                  * when copytool will return progress
1810                  */
1811
1812                 if (car->car_hai->hai_action == HSMA_CANCEL) {
1813                         mdt_cdt_put_request(car);
1814                         continue;
1815                 }
1816
1817                 /* needed size */
1818                 hal_len = sizeof(*hal) + cfs_size_round(MTI_NAME_MAXLEN + 1) +
1819                           cfs_size_round(car->car_hai->hai_len);
1820
1821                 if (hal_len > hal_sz && hal_sz > 0) {
1822                         /* not enough room, free old buffer */
1823                         OBD_FREE(hal, hal_sz);
1824                         hal = NULL;
1825                 }
1826
1827                 /* empty buffer, allocate one */
1828                 if (hal == NULL) {
1829                         hal_sz = hal_len;
1830                         OBD_ALLOC(hal, hal_sz);
1831                         if (hal == NULL) {
1832                                 mdt_cdt_put_request(car);
1833                                 up_read(&cdt->cdt_request_lock);
1834                                 GOTO(out_cdt_state, rc = -ENOMEM);
1835                         }
1836                 }
1837
1838                 hal->hal_version = HAL_VERSION;
1839                 obd_uuid2fsname(hal->hal_fsname, mdt_obd_name(mdt),
1840                                 MTI_NAME_MAXLEN);
1841                 hal->hal_fsname[MTI_NAME_MAXLEN] = '\0';
1842                 hal->hal_archive_id = car->car_archive_id;
1843                 hal->hal_flags = car->car_flags;
1844                 hal->hal_count = 0;
1845
1846                 hai = hai_first(hal);
1847                 memcpy(hai, car->car_hai, car->car_hai->hai_len);
1848                 hai->hai_action = HSMA_CANCEL;
1849                 hal->hal_count = 1;
1850
1851                 /* it is possible to safely call mdt_hsm_agent_send()
1852                  * (ie without a deadlock on cdt_request_lock), because the
1853                  * write lock is taken only if we are not in purge mode
1854                  * (mdt_hsm_agent_send() does not call mdt_cdt_add_request()
1855                  *   nor mdt_cdt_remove_request())
1856                  */
1857                 /* no conflict with cdt thread because cdt is disable and we
1858                  * have the request lock */
1859                 mdt_hsm_agent_send(mti, hal, 1);
1860
1861                 mdt_cdt_put_request(car);
1862         }
1863         up_read(&cdt->cdt_request_lock);
1864
1865         if (hal != NULL)
1866                 OBD_FREE(hal, hal_sz);
1867
1868         /* cancel all on-disk records */
1869         hcad.mdt = mdt;
1870
1871         rc = cdt_llog_process(mti->mti_env, mti->mti_mdt, mdt_cancel_all_cb,
1872                               &hcad, 0, 0, WRITE);
1873 out_cdt_state:
1874         /* Enable coordinator, unless the coordinator was stopping. */
1875         set_cdt_state_locked(cdt, old_state);
1876 out_cdt_state_unlock:
1877         mutex_unlock(&cdt->cdt_state_lock);
1878
1879         lu_context_exit(&session);
1880         lu_context_fini(&session);
1881 out_env:
1882         lu_env_fini(&env);
1883
1884         RETURN(rc);
1885 }
1886
1887 /**
1888  * check if a request is compatible with file status
1889  * \param hai [IN] request description
1890  * \param archive_id [IN] request archive id
1891  * \param rq_flags [IN] request flags
1892  * \param hsm [IN] file HSM metadata
1893  * \retval boolean
1894  */
1895 bool mdt_hsm_is_action_compat(const struct hsm_action_item *hai,
1896                               u32 archive_id, u64 rq_flags,
1897                               const struct md_hsm *hsm)
1898 {
1899         int      is_compat = false;
1900         int      hsm_flags;
1901         ENTRY;
1902
1903         hsm_flags = hsm->mh_flags;
1904         switch (hai->hai_action) {
1905         case HSMA_ARCHIVE:
1906                 if (!(hsm_flags & HS_NOARCHIVE) &&
1907                     (hsm_flags & HS_DIRTY || !(hsm_flags & HS_ARCHIVED)))
1908                         is_compat = true;
1909
1910                 if (hsm_flags & HS_EXISTS &&
1911                     archive_id != 0 &&
1912                     archive_id != hsm->mh_arch_id)
1913                         is_compat = false;
1914
1915                 break;
1916         case HSMA_RESTORE:
1917                 if (!(hsm_flags & HS_DIRTY) && (hsm_flags & HS_RELEASED) &&
1918                     hsm_flags & HS_ARCHIVED && !(hsm_flags & HS_LOST))
1919                         is_compat = true;
1920                 break;
1921         case HSMA_REMOVE:
1922                 if (!(hsm_flags & HS_RELEASED) &&
1923                     (hsm_flags & (HS_ARCHIVED | HS_EXISTS)))
1924                         is_compat = true;
1925                 break;
1926         case HSMA_CANCEL:
1927                 is_compat = true;
1928                 break;
1929         }
1930         CDEBUG(D_HSM, "fid="DFID" action=%s flags=%#llx"
1931                       " extent=%#llx-%#llx hsm_flags=%.8X %s\n",
1932                       PFID(&hai->hai_fid),
1933                       hsm_copytool_action2name(hai->hai_action), rq_flags,
1934                       hai->hai_extent.offset, hai->hai_extent.length,
1935                       hsm->mh_flags,
1936                       (is_compat ? "compatible" : "uncompatible"));
1937
1938         RETURN(is_compat);
1939 }
1940
1941 /*
1942  * sysfs interface used to get/set HSM behaviour (cdt->cdt_policy)
1943  */
1944 static const struct {
1945         __u64            bit;
1946         char            *name;
1947         char            *nickname;
1948 } hsm_policy_names[] = {
1949         { CDT_NONBLOCKING_RESTORE,      "NonBlockingRestore",   "NBR"},
1950         { CDT_NORETRY_ACTION,           "NoRetryAction",        "NRA"},
1951         { 0 },
1952 };
1953
1954 /**
1955  * convert a policy name to a bit
1956  * \param name [IN] policy name
1957  * \retval 0 unknown
1958  * \retval   policy bit
1959  */
1960 static __u64 hsm_policy_str2bit(const char *name)
1961 {
1962         int      i;
1963
1964         for (i = 0; hsm_policy_names[i].bit != 0; i++)
1965                 if (strcmp(hsm_policy_names[i].nickname, name) == 0 ||
1966                     strcmp(hsm_policy_names[i].name, name) == 0)
1967                         return hsm_policy_names[i].bit;
1968         return 0;
1969 }
1970
1971 /**
1972  * convert a policy bit field to a string
1973  * \param mask [IN] policy bit field
1974  * \param hexa [IN] print mask before bit names
1975  * \param buffer [OUT] string
1976  * \param count [IN] size of buffer
1977  */
1978 static void hsm_policy_bit2str(struct seq_file *m, const __u64 mask,
1979                                 const bool hexa)
1980 {
1981         int      i, j;
1982         __u64    bit;
1983         ENTRY;
1984
1985         if (hexa)
1986                 seq_printf(m, "(%#llx) ", mask);
1987
1988         for (i = 0; i < CDT_POLICY_SHIFT_COUNT; i++) {
1989                 bit = (1ULL << i);
1990
1991                 for (j = 0; hsm_policy_names[j].bit != 0; j++) {
1992                         if (hsm_policy_names[j].bit == bit)
1993                                 break;
1994                 }
1995                 if (bit & mask)
1996                         seq_printf(m, "[%s] ", hsm_policy_names[j].name);
1997                 else
1998                         seq_printf(m, "%s ", hsm_policy_names[j].name);
1999         }
2000         /* remove last ' ' */
2001         m->count--;
2002         seq_putc(m, '\n');
2003 }
2004
2005 /* methods to read/write HSM policy flags */
2006 static int mdt_hsm_policy_seq_show(struct seq_file *m, void *data)
2007 {
2008         struct mdt_device       *mdt = m->private;
2009         struct coordinator      *cdt = &mdt->mdt_coordinator;
2010         ENTRY;
2011
2012         hsm_policy_bit2str(m, cdt->cdt_policy, false);
2013         RETURN(0);
2014 }
2015
2016 static ssize_t
2017 mdt_hsm_policy_seq_write(struct file *file, const char __user *buffer,
2018                          size_t count, loff_t *off)
2019 {
2020         struct seq_file         *m = file->private_data;
2021         struct mdt_device       *mdt = m->private;
2022         struct coordinator      *cdt = &mdt->mdt_coordinator;
2023         char                    *start, *token, sign;
2024         char                    *buf;
2025         __u64                    policy;
2026         __u64                    add_mask, remove_mask, set_mask;
2027         int                      rc;
2028         ENTRY;
2029
2030         if (count + 1 > PAGE_SIZE)
2031                 RETURN(-EINVAL);
2032
2033         OBD_ALLOC(buf, count + 1);
2034         if (buf == NULL)
2035                 RETURN(-ENOMEM);
2036
2037         if (copy_from_user(buf, buffer, count))
2038                 GOTO(out, rc = -EFAULT);
2039
2040         buf[count] = '\0';
2041
2042         start = buf;
2043         CDEBUG(D_HSM, "%s: receive new policy: '%s'\n", mdt_obd_name(mdt),
2044                start);
2045
2046         add_mask = remove_mask = set_mask = 0;
2047         do {
2048                 token = strsep(&start, "\n ");
2049                 sign = *token;
2050
2051                 if (sign == '\0')
2052                         continue;
2053
2054                 if (sign == '-' || sign == '+')
2055                         token++;
2056
2057                 policy = hsm_policy_str2bit(token);
2058                 if (policy == 0) {
2059                         CWARN("%s: '%s' is unknown, "
2060                               "supported policies are:\n", mdt_obd_name(mdt),
2061                               token);
2062                         hsm_policy_bit2str(m, 0, false);
2063                         GOTO(out, rc = -EINVAL);
2064                 }
2065                 switch (sign) {
2066                 case '-':
2067                         remove_mask |= policy;
2068                         break;
2069                 case '+':
2070                         add_mask |= policy;
2071                         break;
2072                 default:
2073                         set_mask |= policy;
2074                         break;
2075                 }
2076
2077         } while (start != NULL);
2078
2079         CDEBUG(D_HSM, "%s: new policy: rm=%#llx add=%#llx set=%#llx\n",
2080                mdt_obd_name(mdt), remove_mask, add_mask, set_mask);
2081
2082         /* if no sign in all string, it is a clear and set
2083          * if some sign found, all unsigned are converted
2084          * to add
2085          * P1 P2 = set to P1 and P2
2086          * P1 -P2 = add P1 clear P2 same as +P1 -P2
2087          */
2088         if (remove_mask == 0 && add_mask == 0) {
2089                 cdt->cdt_policy = set_mask;
2090         } else {
2091                 cdt->cdt_policy |= set_mask | add_mask;
2092                 cdt->cdt_policy &= ~remove_mask;
2093         }
2094
2095         GOTO(out, rc = count);
2096
2097 out:
2098         OBD_FREE(buf, count + 1);
2099         RETURN(rc);
2100 }
2101 LDEBUGFS_SEQ_FOPS(mdt_hsm_policy);
2102
2103 ssize_t loop_period_show(struct kobject *kobj, struct attribute *attr,
2104                          char *buf)
2105 {
2106         struct coordinator *cdt = container_of(kobj, struct coordinator,
2107                                                cdt_hsm_kobj);
2108
2109         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_loop_period);
2110 }
2111
2112 ssize_t loop_period_store(struct kobject *kobj, struct attribute *attr,
2113                           const char *buffer, size_t count)
2114 {
2115         struct coordinator *cdt = container_of(kobj, struct coordinator,
2116                                                cdt_hsm_kobj);
2117         unsigned int val;
2118         int rc;
2119
2120         rc = kstrtouint(buffer, 0, &val);
2121         if (rc)
2122                 return rc;
2123
2124         if (val != 0)
2125                 cdt->cdt_loop_period = val;
2126
2127         return val ? count : -EINVAL;
2128 }
2129 LUSTRE_RW_ATTR(loop_period);
2130
2131 ssize_t grace_delay_show(struct kobject *kobj, struct attribute *attr,
2132                          char *buf)
2133 {
2134         struct coordinator *cdt = container_of(kobj, struct coordinator,
2135                                                cdt_hsm_kobj);
2136
2137         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_grace_delay);
2138 }
2139
2140 ssize_t grace_delay_store(struct kobject *kobj, struct attribute *attr,
2141                           const char *buffer, size_t count)
2142 {
2143         struct coordinator *cdt = container_of(kobj, struct coordinator,
2144                                                cdt_hsm_kobj);
2145         unsigned int val;
2146         int rc;
2147
2148         rc = kstrtouint(buffer, 0, &val);
2149         if (rc)
2150                 return rc;
2151
2152         if (val != 0)
2153                 cdt->cdt_grace_delay = val;
2154
2155         return val ? count : -EINVAL;
2156 }
2157 LUSTRE_RW_ATTR(grace_delay);
2158
2159 ssize_t active_request_timeout_show(struct kobject *kobj,
2160                                     struct attribute *attr,
2161                                     char *buf)
2162 {
2163         struct coordinator *cdt = container_of(kobj, struct coordinator,
2164                                                cdt_hsm_kobj);
2165
2166         return scnprintf(buf, PAGE_SIZE, "%d\n", cdt->cdt_active_req_timeout);
2167 }
2168
2169 ssize_t active_request_timeout_store(struct kobject *kobj,
2170                                      struct attribute *attr,
2171                                      const char *buffer, size_t count)
2172 {
2173         struct coordinator *cdt = container_of(kobj, struct coordinator,
2174                                                cdt_hsm_kobj);
2175         unsigned int val;
2176         int rc;
2177
2178         rc = kstrtouint(buffer, 0, &val);
2179         if (rc)
2180                 return rc;
2181
2182         if (val != 0)
2183                 cdt->cdt_active_req_timeout = val;
2184
2185         return val ? count : -EINVAL;
2186 }
2187 LUSTRE_RW_ATTR(active_request_timeout);
2188
2189 ssize_t max_requests_show(struct kobject *kobj, struct attribute *attr,
2190                           char *buf)
2191 {
2192         struct coordinator *cdt = container_of(kobj, struct coordinator,
2193                                                cdt_hsm_kobj);
2194
2195         return scnprintf(buf, PAGE_SIZE, "%llu\n", cdt->cdt_max_requests);
2196 }
2197
2198 ssize_t max_requests_store(struct kobject *kobj, struct attribute *attr,
2199                            const char *buffer, size_t count)
2200 {
2201         struct coordinator *cdt = container_of(kobj, struct coordinator,
2202                                                cdt_hsm_kobj);
2203         unsigned long long val;
2204         int rc;
2205
2206         rc = kstrtoull(buffer, 0, &val);
2207         if (rc)
2208                 return rc;
2209
2210         if (val != 0)
2211                 cdt->cdt_max_requests = val;
2212
2213         return val ? count : -EINVAL;
2214 }
2215 LUSTRE_RW_ATTR(max_requests);
2216
2217 ssize_t default_archive_id_show(struct kobject *kobj, struct attribute *attr,
2218                                 char *buf)
2219 {
2220         struct coordinator *cdt = container_of(kobj, struct coordinator,
2221                                                cdt_hsm_kobj);
2222
2223         return scnprintf(buf, PAGE_SIZE, "%u\n", cdt->cdt_default_archive_id);
2224 }
2225
2226 ssize_t default_archive_id_store(struct kobject *kobj, struct attribute *attr,
2227                                  const char *buffer, size_t count)
2228 {
2229         struct coordinator *cdt = container_of(kobj, struct coordinator,
2230                                                cdt_hsm_kobj);
2231         unsigned int val;
2232         int rc;
2233
2234         rc = kstrtouint(buffer, 0, &val);
2235         if (rc)
2236                 return rc;
2237
2238         if (val != 0)
2239                 cdt->cdt_default_archive_id = val;
2240
2241         return val ? count : -EINVAL;
2242 }
2243 LUSTRE_RW_ATTR(default_archive_id);
2244
2245 /*
2246  * procfs write method for MDT/hsm_control
2247  * proc entry is in mdt directory so data is mdt obd_device pointer
2248  */
2249 #define CDT_ENABLE_CMD   "enabled"
2250 #define CDT_STOP_CMD     "shutdown"
2251 #define CDT_DISABLE_CMD  "disabled"
2252 #define CDT_PURGE_CMD    "purge"
2253 #define CDT_HELP_CMD     "help"
2254 #define CDT_MAX_CMD_LEN  10
2255
2256 ssize_t hsm_control_store(struct kobject *kobj, struct attribute *attr,
2257                           const char *buffer, size_t count)
2258 {
2259         struct obd_device *obd = container_of(kobj, struct obd_device,
2260                                               obd_kset.kobj);
2261         struct mdt_device *mdt = mdt_dev(obd->obd_lu_dev);
2262         struct coordinator *cdt = &(mdt->mdt_coordinator);
2263         int usage = 0;
2264         int rc = 0;
2265
2266         if (count == 0 || count >= CDT_MAX_CMD_LEN)
2267                 return -EINVAL;
2268
2269         if (strncmp(buffer, CDT_ENABLE_CMD, strlen(CDT_ENABLE_CMD)) == 0) {
2270                 if (cdt->cdt_state == CDT_DISABLE) {
2271                         rc = set_cdt_state(cdt, CDT_RUNNING);
2272                         mdt_hsm_cdt_event(cdt);
2273                         wake_up(&cdt->cdt_waitq);
2274                 } else if (cdt->cdt_state == CDT_RUNNING) {
2275                         rc = 0;
2276                 } else {
2277                         rc = mdt_hsm_cdt_start(mdt);
2278                 }
2279         } else if (strncmp(buffer, CDT_STOP_CMD, strlen(CDT_STOP_CMD)) == 0) {
2280                 if (cdt->cdt_state == CDT_STOPPING) {
2281                         CERROR("%s: Coordinator is already stopping\n",
2282                                mdt_obd_name(mdt));
2283                         rc = -EALREADY;
2284                 } else if (cdt->cdt_state == CDT_STOPPED) {
2285                         rc = 0;
2286                 } else {
2287                         rc = mdt_hsm_cdt_stop(mdt);
2288                 }
2289         } else if (strncmp(buffer, CDT_DISABLE_CMD,
2290                            strlen(CDT_DISABLE_CMD)) == 0) {
2291                 if ((cdt->cdt_state == CDT_STOPPING) ||
2292                     (cdt->cdt_state == CDT_STOPPED)) {
2293                         CERROR("%s: Coordinator is stopped\n",
2294                                mdt_obd_name(mdt));
2295                         rc = -EINVAL;
2296                 } else {
2297                         rc = set_cdt_state(cdt, CDT_DISABLE);
2298                 }
2299         } else if (strncmp(buffer, CDT_PURGE_CMD,
2300                            strlen(CDT_PURGE_CMD)) == 0) {
2301                 rc = hsm_cancel_all_actions(mdt);
2302         } else if (strncmp(buffer, CDT_HELP_CMD,
2303                            strlen(CDT_HELP_CMD)) == 0) {
2304                 usage = 1;
2305         } else {
2306                 usage = 1;
2307                 rc = -EINVAL;
2308         }
2309
2310         if (usage == 1)
2311                 CERROR("%s: Valid coordinator control commands are: "
2312                        "%s %s %s %s %s\n", mdt_obd_name(mdt),
2313                        CDT_ENABLE_CMD, CDT_STOP_CMD, CDT_DISABLE_CMD,
2314                        CDT_PURGE_CMD, CDT_HELP_CMD);
2315
2316         if (rc)
2317                 RETURN(rc);
2318
2319         RETURN(count);
2320 }
2321
2322 ssize_t hsm_control_show(struct kobject *kobj, struct attribute *attr,
2323                          char *buf)
2324 {
2325         struct obd_device *obd = container_of(kobj, struct obd_device,
2326                                               obd_kset.kobj);
2327         struct coordinator *cdt;
2328
2329         cdt = &(mdt_dev(obd->obd_lu_dev)->mdt_coordinator);
2330
2331         return scnprintf(buf, PAGE_SIZE, "%s\n",
2332                          cdt_mdt_state2str(cdt->cdt_state));
2333 }
2334
2335 static int
2336 mdt_hsm_request_mask_show(struct seq_file *m, __u64 mask)
2337 {
2338         bool first = true;
2339         int i;
2340         ENTRY;
2341
2342         for (i = 0; i < 8 * sizeof(mask); i++) {
2343                 if (mask & (1UL << i)) {
2344                         seq_printf(m, "%s%s", first ? "" : " ",
2345                                    hsm_copytool_action2name(i));
2346                         first = false;
2347                 }
2348         }
2349         seq_putc(m, '\n');
2350
2351         RETURN(0);
2352 }
2353
2354 static int
2355 mdt_hsm_user_request_mask_seq_show(struct seq_file *m, void *data)
2356 {
2357         struct mdt_device *mdt = m->private;
2358         struct coordinator *cdt = &mdt->mdt_coordinator;
2359
2360         return mdt_hsm_request_mask_show(m, cdt->cdt_user_request_mask);
2361 }
2362
2363 static int
2364 mdt_hsm_group_request_mask_seq_show(struct seq_file *m, void *data)
2365 {
2366         struct mdt_device *mdt = m->private;
2367         struct coordinator *cdt = &mdt->mdt_coordinator;
2368
2369         return mdt_hsm_request_mask_show(m, cdt->cdt_group_request_mask);
2370 }
2371
2372 static int
2373 mdt_hsm_other_request_mask_seq_show(struct seq_file *m, void *data)
2374 {
2375         struct mdt_device *mdt = m->private;
2376         struct coordinator *cdt = &mdt->mdt_coordinator;
2377
2378         return mdt_hsm_request_mask_show(m, cdt->cdt_other_request_mask);
2379 }
2380
2381 static inline enum hsm_copytool_action
2382 hsm_copytool_name2action(const char *name)
2383 {
2384         if (strcasecmp(name, "NOOP") == 0)
2385                 return HSMA_NONE;
2386         else if (strcasecmp(name, "ARCHIVE") == 0)
2387                 return HSMA_ARCHIVE;
2388         else if (strcasecmp(name, "RESTORE") == 0)
2389                 return HSMA_RESTORE;
2390         else if (strcasecmp(name, "REMOVE") == 0)
2391                 return HSMA_REMOVE;
2392         else if (strcasecmp(name, "CANCEL") == 0)
2393                 return HSMA_CANCEL;
2394         else
2395                 return -1;
2396 }
2397
2398 static ssize_t
2399 mdt_write_hsm_request_mask(struct file *file, const char __user *user_buf,
2400                             size_t user_count, __u64 *mask)
2401 {
2402         char *buf, *pos, *name;
2403         size_t buf_size;
2404         __u64 new_mask = 0;
2405         int rc;
2406         ENTRY;
2407
2408         if (!(user_count < 4096))
2409                 RETURN(-ENOMEM);
2410
2411         buf_size = user_count + 1;
2412
2413         OBD_ALLOC(buf, buf_size);
2414         if (buf == NULL)
2415                 RETURN(-ENOMEM);
2416
2417         if (copy_from_user(buf, user_buf, buf_size - 1))
2418                 GOTO(out, rc = -EFAULT);
2419
2420         buf[buf_size - 1] = '\0';
2421
2422         pos = buf;
2423         while ((name = strsep(&pos, " \t\v\n")) != NULL) {
2424                 int action;
2425
2426                 if (*name == '\0')
2427                         continue;
2428
2429                 action = hsm_copytool_name2action(name);
2430                 if (action < 0)
2431                         GOTO(out, rc = -EINVAL);
2432
2433                 new_mask |= (1UL << action);
2434         }
2435
2436         *mask = new_mask;
2437         rc = user_count;
2438 out:
2439         OBD_FREE(buf, buf_size);
2440
2441         RETURN(rc);
2442 }
2443
2444 static ssize_t
2445 mdt_hsm_user_request_mask_seq_write(struct file *file, const char __user *buf,
2446                                         size_t count, loff_t *off)
2447 {
2448         struct seq_file         *m = file->private_data;
2449         struct mdt_device       *mdt = m->private;
2450         struct coordinator *cdt = &mdt->mdt_coordinator;
2451
2452         return mdt_write_hsm_request_mask(file, buf, count,
2453                                            &cdt->cdt_user_request_mask);
2454 }
2455
2456 static ssize_t
2457 mdt_hsm_group_request_mask_seq_write(struct file *file, const char __user *buf,
2458                                         size_t count, loff_t *off)
2459 {
2460         struct seq_file         *m = file->private_data;
2461         struct mdt_device       *mdt = m->private;
2462         struct coordinator      *cdt = &mdt->mdt_coordinator;
2463
2464         return mdt_write_hsm_request_mask(file, buf, count,
2465                                            &cdt->cdt_group_request_mask);
2466 }
2467
2468 static ssize_t
2469 mdt_hsm_other_request_mask_seq_write(struct file *file, const char __user *buf,
2470                                         size_t count, loff_t *off)
2471 {
2472         struct seq_file         *m = file->private_data;
2473         struct mdt_device       *mdt = m->private;
2474         struct coordinator      *cdt = &mdt->mdt_coordinator;
2475
2476         return mdt_write_hsm_request_mask(file, buf, count,
2477                                            &cdt->cdt_other_request_mask);
2478 }
2479
2480 static ssize_t remove_archive_on_last_unlink_show(struct kobject *kobj,
2481                                                   struct attribute *attr,
2482                                                   char *buf)
2483 {
2484         struct coordinator *cdt = container_of(kobj, struct coordinator,
2485                                                cdt_hsm_kobj);
2486
2487         return scnprintf(buf, PAGE_SIZE, "%u\n",
2488                          cdt->cdt_remove_archive_on_last_unlink);
2489 }
2490
2491 static ssize_t remove_archive_on_last_unlink_store(struct kobject *kobj,
2492                                                    struct attribute *attr,
2493                                                    const char *buffer,
2494                                                    size_t count)
2495 {
2496         struct coordinator *cdt = container_of(kobj, struct coordinator,
2497                                                cdt_hsm_kobj);
2498         bool val;
2499         int rc;
2500
2501         rc = kstrtobool(buffer, &val);
2502         if (rc < 0)
2503                 return rc;
2504
2505         cdt->cdt_remove_archive_on_last_unlink = val;
2506         return count;
2507 }
2508 LUSTRE_RW_ATTR(remove_archive_on_last_unlink);
2509
2510 LDEBUGFS_SEQ_FOPS(mdt_hsm_user_request_mask);
2511 LDEBUGFS_SEQ_FOPS(mdt_hsm_group_request_mask);
2512 LDEBUGFS_SEQ_FOPS(mdt_hsm_other_request_mask);
2513
2514 /* Read-only sysfs files for request counters */
2515 static ssize_t archive_count_show(struct kobject *kobj, struct attribute *attr,
2516                                   char *buf)
2517 {
2518         struct coordinator *cdt = container_of(kobj, struct coordinator,
2519                                                cdt_hsm_kobj);
2520
2521         return scnprintf(buf, PAGE_SIZE, "%d\n",
2522                          atomic_read(&cdt->cdt_archive_count));
2523 }
2524 LUSTRE_RO_ATTR(archive_count);
2525
2526 static ssize_t restore_count_show(struct kobject *kobj, struct attribute *attr,
2527                                   char *buf)
2528 {
2529         struct coordinator *cdt = container_of(kobj, struct coordinator,
2530                                                cdt_hsm_kobj);
2531
2532         return scnprintf(buf, PAGE_SIZE, "%d\n",
2533                          atomic_read(&cdt->cdt_restore_count));
2534 }
2535 LUSTRE_RO_ATTR(restore_count);
2536
2537 static ssize_t remove_count_show(struct kobject *kobj, struct attribute *attr,
2538                                  char *buf)
2539 {
2540         struct coordinator *cdt = container_of(kobj, struct coordinator,
2541                                                cdt_hsm_kobj);
2542
2543         return scnprintf(buf, PAGE_SIZE, "%d\n",
2544                          atomic_read(&cdt->cdt_remove_count));
2545 }
2546 LUSTRE_RO_ATTR(remove_count);
2547
2548 static struct ldebugfs_vars ldebugfs_mdt_hsm_vars[] = {
2549         { .name =       "agents",
2550           .fops =       &mdt_hsm_agent_fops                     },
2551         { .name =       "actions",
2552           .fops =       &mdt_hsm_actions_fops,
2553           .proc_mode =  0444                                    },
2554         { .name =       "policy",
2555           .fops =       &mdt_hsm_policy_fops                    },
2556         { .name =       "active_requests",
2557           .fops =       &mdt_hsm_active_requests_fops           },
2558         { .name =       "user_request_mask",
2559           .fops =       &mdt_hsm_user_request_mask_fops,        },
2560         { .name =       "group_request_mask",
2561           .fops =       &mdt_hsm_group_request_mask_fops,       },
2562         { .name =       "other_request_mask",
2563           .fops =       &mdt_hsm_other_request_mask_fops,       },
2564         { 0 }
2565 };
2566
2567 static struct attribute *hsm_attrs[] = {
2568         &lustre_attr_loop_period.attr,
2569         &lustre_attr_grace_delay.attr,
2570         &lustre_attr_active_request_timeout.attr,
2571         &lustre_attr_max_requests.attr,
2572         &lustre_attr_default_archive_id.attr,
2573         &lustre_attr_remove_archive_on_last_unlink.attr,
2574         &lustre_attr_archive_count.attr,
2575         &lustre_attr_restore_count.attr,
2576         &lustre_attr_remove_count.attr,
2577         NULL,
2578 };
2579
2580 static void hsm_kobj_release(struct kobject *kobj)
2581 {
2582         struct coordinator *cdt = container_of(kobj, struct coordinator,
2583                                                cdt_hsm_kobj);
2584
2585         debugfs_remove_recursive(cdt->cdt_debugfs_dir);
2586         cdt->cdt_debugfs_dir = NULL;
2587
2588         complete(&cdt->cdt_kobj_unregister);
2589 }
2590
2591 static struct kobj_type hsm_ktype = {
2592         .default_attrs  = hsm_attrs,
2593         .sysfs_ops      = &lustre_sysfs_ops,
2594         .release        = hsm_kobj_release,
2595 };
2596
2597 /**
2598  * create sysfs entries for coordinator
2599  * \param mdt [IN]
2600  * \retval 0 success
2601  * \retval -ve failure
2602  */
2603 int hsm_cdt_tunables_init(struct mdt_device *mdt)
2604 {
2605         struct coordinator *cdt = &mdt->mdt_coordinator;
2606         struct obd_device *obd = mdt2obd_dev(mdt);
2607         int rc;
2608
2609         init_completion(&cdt->cdt_kobj_unregister);
2610         rc = kobject_init_and_add(&cdt->cdt_hsm_kobj, &hsm_ktype,
2611                                   &obd->obd_kset.kobj, "%s", "hsm");
2612         if (rc) {
2613                 kobject_put(&cdt->cdt_hsm_kobj);
2614                 return rc;
2615         }
2616
2617         /* init debugfs entries, failure is not critical */
2618         cdt->cdt_debugfs_dir = debugfs_create_dir("hsm",
2619                                                   obd->obd_debugfs_entry);
2620         ldebugfs_add_vars(cdt->cdt_debugfs_dir, ldebugfs_mdt_hsm_vars, mdt);
2621
2622         return 0;
2623 }
2624
2625 /**
2626  * remove sysfs entries for coordinator
2627  *
2628  * @mdt
2629  */
2630 void hsm_cdt_tunables_fini(struct mdt_device *mdt)
2631 {
2632         struct coordinator *cdt = &mdt->mdt_coordinator;
2633
2634         kobject_put(&cdt->cdt_hsm_kobj);
2635         wait_for_completion(&cdt->cdt_kobj_unregister);
2636 }