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