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